What is the Spring equivalent for CDI's Instance, or Guices Provider

前端 未结 2 1092
北恋
北恋 2020-12-14 08:42

In CDI you can define an object that will give you items of a certain type, using:

@Inject
Instance myObj         


        
相关标签:
2条回答
  • 2020-12-14 09:09

    So after a lot of digging around I found out that Spring supports JSR-330. This JSR defines a simple API - the whole spec is literally just this API - that standardizes several dependency injection interfaces, annotations and behaviors.

    Unlike Spring's FactoryBean the javax.inject.Provider interface doesn't throws Exception on getting the bean reference. Furthermore, you would still need to define this FactoryBean in some place (read XML, or @Configuration class, and this is suboptimal).

    Due to a bug, in current Spring 3.1.1, the javax.inject.Provider does not work. It does work in Spring 3.1.0.

    In order to use it you simple need to include the javax.inject jar - if you use maven you can:

        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>
    

    Spring will detect it, and from that moment on you can simply:

    @Inject
    Provider<MyObject> myObjectInstance;
    //...
    MyObject myObjectInstance.get();
    

    like in the Guice example, since it is the same API.

    Despite my previous comment to Konstantin, Spring does create the Provider by itself. (I was testing it against Spring 3.1.1 and run into this Spring Provider regression issue)

    0 讨论(0)
  • 2020-12-14 09:16

    Sounds like a FactoryBean

    0 讨论(0)
提交回复
热议问题