Spring - Using JSR 330 Provider to Inject Narrower Scoped Bean

[Last Updated: Nov 19, 2016]

Spring 3.0, started support for JSR-330 standard annotations (Dependency Injection). That means now we can use @javax.inject.Inject instead of @Autowire along with other standard annotations and interfaces.

To solve narrowing scoped bean injection problem, we now have a standard option, i.e. using javax.inject.Provider<T> interface. We can inject or autowire the Provider interface having component type parameter as our prototype bean:

    private Provider<MyPrototypeBean> myPrototypeBeanProvider;

According to the specification, Provider.get() will always return the new instance of type T, in our case MyPrototypeBean.

We won't need any other extra configuration in @Configuration class. We just have to return instance of MyPrototypeBean bean from one of the factory method, annotated with @Bean.

Having this interface injected has other advantages as well e.g. lazy retrieval of an instance etc.

The good thing is, this approach doesn't involve any runtime byte code generation but it's just like Spring's ObjectFactory implementation. ObjectFactory is Spring specific alternative to Provider interface. In the following example with can replace Provider with ObjectFactory without any other change.

Example Project

We are going to use the previous example to demonstrate how to inject Provider for our MyPrototypeBean

We have to add javax.inject dependency in our pom.xml this time.

Dependencies and Technologies Used:

  • Spring Context 4.2.3.RELEASE: Spring Context.
  • javax.inject 1: The javax.inject API.
  • JDK 1.8
  • Maven 3.0.4

Spring Provider Example Select All Download
  • spring-provider-example
    • src
      • main
        • java
          • com
            • logicbig
              • example

    See Also