【问题标题】:How to do Spring Lookup Method Injection with Annotations?如何使用注解进行 Spring Lookup 方法注入?
【发布时间】:2011-04-22 23:06:33
【问题描述】:

有没有办法通过注解来使用查找方法注入?

给定以下类:

@Service
public abstract class A {


    protected abstract createB();

}

为了让它工作,我必须在 spring applicationContext.xml 中声明以下内容:

<bean id="b" class="com.xyz.B">
</bean>

<bean id="a" class="com.xyz.A">
    <lookup-method name="createB" bean="b"/>
</bean>

即使我使用的是&lt;context:component-scan base&gt;,我也必须在 XML 中声明它。我认为这不是一个好方法。

注解怎么做?

【问题讨论】:

    标签: spring dependency-injection spring-annotations


    【解决方案1】:

    仅使用 Spring >= 4.1 实现,请参阅ticket

    【讨论】:

    • 在 Spring Framework 4.1 中,它可用作 \@Lookup 注释。请参阅@Danny-Dan 的回答。
    • 谢谢,更新了我的答案
    【解决方案2】:

    最后引入@Lookup注解。这是discussion 的使用方法。

    【讨论】:

    • @Lookup 注解需要 Spring 4.1 或更高版本
    【解决方案3】:

    如果你想跟上 Spring API 的步伐,org.springframework.beans.factory.ObjectFactory 也是可能的

    public class MySingleton {
    
      @Autowired
      private ObjectFactory<MyPrototype> myPrototypeFactory;
    
      public void operation() {
        MyPrototype instance = myPrototypeFactory.getObject();
        // do something with the instance
      }
    }
    

    您可以在documentation 中阅读更多内容。

    【讨论】:

      【解决方案4】:

      可以使用javax.inject.Provider。感谢Phil Webb

      public class MySingleton {
      
        @Autowired
        private Provider<MyPrototype> myPrototype;
      
        public void operation() {
          MyPrototype instance = myPrototype.get();
          // do something with the instance
        }
      
      }
      

      【讨论】:

      • 请注意下面关于@Lookup 的答案——Spring 4.1 或更高版本可以使用注释。尽管我认为 Provider 在阅读代码时更加简洁且不那么混乱。
      猜你喜欢
      • 2014-11-19
      • 1970-01-01
      • 2016-05-04
      • 2012-02-11
      • 1970-01-01
      • 2015-01-30
      • 1970-01-01
      • 2012-05-29
      • 1970-01-01
      相关资源
      最近更新 更多