Contact Us 1-800-596-4880

Dependency Injection

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:

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
    }
}

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.