【问题标题】:Can spring container inject collaborators using custom methods?spring 容器可以使用自定义方法注入协作者吗?
【发布时间】:2011-03-22 17:14:26
【问题描述】:

通常通过以下配置 (http://static.springsource.org/sprin...beans-beanname) 通过 setter 注入依赖项:

<bean id="exampleBean" class="examples.ExampleBean">
    <!-- setter injection using the nested <ref/> element -->
    <property name="beanOne"><ref bean="anotherExampleBean"/></property>

    <!-- setter injection using the neater 'ref' attribute -->
    <property name="beanTwo" ref="yetAnotherBean"/>
    <property name="integerProperty" value="1"/>
</bean>

<bean id="anotherExampleBean" class="examples.AnotherBean"/>
<bean id="yetAnotherBean" class="examples.YetAnotherBean"/>

假设类 examples.ExampleBean 有一个集合侦听器对象,而方法 addListener(SomeListenerInterface) 是添加侦听器的唯一可能方法。我可以像使用属性设置器那样在 xml 中以声明方式注入侦听器吗?

【问题讨论】:

    标签: java spring dependency-injection inversion-of-control


    【解决方案1】:

    您可能会想出一些巴洛克式的机制来在 XML 中完成这一切,但最简洁的方法是使用 FactoryBean。你编写了一个实现FactoryBean 的类,它负责构造和配置你的目标对象(参见Spring docs)。您的 FactoryBean 将具有所需的 getter/setter/autowiring,并将它们注入到目标对象中。

    这通常是在 Spring 中处理非 javabean 最简洁的方法,尤其是在您无法修改目标类的情况下。

    【讨论】:

      【解决方案2】:

      这里是属性元素定义

      属性元素对应于 bean 类公开的 JavaBean setter 方法

      为了达到你的目标,你可以使用@Autowired 注解。 即使使用任意名称也可以使用

      @Autowired
      public void inject(SomeListenerInterface someListenerInterface) {
          this.someListenerInterface = someListenerInterface;
      }
      

      【讨论】:

      • 这是可能的,但它会自动在所有声明此属性的 bean 中注入所有 'SomeListenerInterface' bean。无论如何,谢谢你的信息,我不知道这个属性。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-12
      • 2011-04-03
      • 2017-01-01
      • 1970-01-01
      • 2012-04-27
      相关资源
      最近更新 更多