public class MyCommand implements Command {
@Inject
private MuleContext muleContext;
@Inject
private ObjectStoreManager objectStoreManager;
@Inject
private QueueManager queueManager;
private String userId;
private String moreNotReusableStuff;
public void execute() {
// Magic happens here
}
}
Dependency Injection
Mule Runtime Engine versions 3.5, 3.6, and 3.7 reached End of Life on or before January 25, 2020. For more information, contact your Customer Success Manager to determine how you can migrate to the latest Mule version. |
This guide helps you use dependency injection. For registry information, see Unifying the Mule Registry.
Notes:
-
MuleSoft supports Dependency Injection as defined in JSR-330
-
You can inject objects either by using the @Inject annotation or with Spring Beans
-
You can inject objects that might not be in the registry, but the values to be injected are in the registry
-
By default Mule has only one registry (starting with 3.7), but if you add more registries, you cannot do cross-registry injections
Using Dependency Injection
To use dependency injection to wire objects in the registry together, you can inject dependencies into objects that are not necessarily registered. For example, suppose you are building a custom component which uses the command design pattern, and suppose that you have a command that requires the MuleContext, the ObjectStoreManager, and the QueueManager while also carrying a custom state which prevents you from making that instance reusable (as it’s often the case with the command pattern).
The command object looks like this:
You can view gistfile1.java in GitHub.
You only need one instance of each of those commands per MuleEvent your component receives.
Register the instance of dependency injection as follows:
Command command = muleContext.getInjector().inject(new MyCommand());
You can view gistfile1.java in GitHub
Starting with 3.7, there is a new API in Mule called Injector
which is capable of injecting dependencies into a JSR-330 annotated object. Injected instances do not go into the registry because of it.