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.
最佳答案
您尝试将MyObjectFactory类型的对象注入到path.to.Foo中,在其中应该有MyObject类型的对象.请按以下方式更改您的代码:
原文链接:https://www.f2er.com/spring/531859.htmlFoo:
public class Foo {
private MyObject myObject;
public void setMyObject(MyObject value) { myObject=value;}
}
MyObjectFactory:
public class MyObjectFactory {
public MyObject getService() {
return new MyObject();
}
}
春季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 ...>在您的情况下表达相同的内容,因此您可以忽略其中一个.
更新:
我以为您不想要单例,这就是为什么我添加了scope =“ prototype”.如果您的MyObject实例假定为单例,请将其删除.