Spring - 从工厂类中注入bean

时间:2014-02-19 07:11:07

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

我班上有以下内容:

public class Manager {        
    private Apple apple = AppleFactory.createInstance();
    // .....
}

appContext.xml:

<bean id="manager" class="Manager"/>

AppleFactory是一个我无法控制的外部库。我使用xml配置(appContext.xml)来连接bean。如何从appContext.xml注入field apple?

3 个答案:

答案 0 :(得分:4)

<bean id="apple" class="AppleFactory" factory-method="createInstance" />
<bean id="manager" class="Manager"/>
<context:annotation-config />

你的经理

public class Manager {

    @Autowired
    private Apple apple;

}

应该做的伎俩。

请参阅the reference guideInitializing Spring bean from static method from another Class?

答案 1 :(得分:2)

您可以使用以下配置:

<bean id="apple" class="jarpackagename.AppleFactory"
      factory-method="createInstance">
</bean>

<bean id="manager" class="pkgname.Manager">
    <property name="apple" ref="apple">
</bean>

答案 2 :(得分:1)

您可以按如下方式配置Manager bean

<bean class="xxx.Manager">
    <property name="apple">
        <bean class="yyy.AppleFactory" factory-method="createInstance" />
    </property>
</bean>