使用工厂方法的Spring autowire对象

时间:2012-11-14 02:49:13

标签: java spring

我正在试图找出如何将这个java代码更改为spring

private MyObject myObject = MyObjectFactory.getService();

在我的Foo.java类中,我有

@Autowired
private MyObject myObject;

在spring xml中,我有:

<bean id="MyObject" class="path.to.MyObjectFactory" factory-method="getService"></bean>

<bean id="Foo" class="path.to.Foo">
    <property name="myObject" ref="MyObject"/>
</bean>

错误是

No matching bean of type [path.to.MyObject] found for dependency: 
expected at least 1 bean which qualifies as autowire candidate for this dependency.

1 个答案:

答案 0 :(得分:3)

您尝试将类型为MyObjectFactory的对象注入path.to.Foo,其中需要类型为MyObject的对象。请改变你的代码:

富:

public class Foo {
    private MyObject myObject;
    public void setMyObject(MyObject value) { myObject=value;}
}

MyObjectFactory:

public class MyObjectFactory {
    public MyObject getService() {
        return new MyObject();
    }
}

spring xml:

<bean class="MyObjectFactory" id="factory" />
<bean id="myObject" factory-bean="factory" factory-method="getService" scope="prototype" />

<bean id="Foo" class="path.to.Foo">
    <property name="myObject" ref="MyObject"/>
</bean>

顺便说一下,@Autowired<property ...>在你的情况下表达同样的事情,所以你可以将这一个留在那里。

<强>更新

看一下here,了解春季工厂bean的更多信息。

我假设你不想要单身,这就是我添加scope="prototype"的原因。如果您的MyObject实例假设是单身人士,请将其删除。