jb.
jb.

Reputation: 10361

Spring autowire object using factory method

I'm trying to figure out how to change this java code into spring

private MyObject myObject = MyObjectFactory.getService();

In my Foo.java class I have

@Autowired
private MyObject myObject;

In the spring xml, I have:

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

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

The error is

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

Upvotes: 3

Views: 7989

Answers (1)

Yevgeniy
Yevgeniy

Reputation: 2694

you try to inject a object of type MyObjectFactory into path.to.Foo, where a object of type MyObject is expected. please change your code like this:

Foo:

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>

By the way, @Autowired and <property ...> express the same thing in your case, so you could leave the one or the other out.

UPDATE:

take a look here for more information factory beans in spring.

i assumed you do not want a singleton, that is why i added scope="prototype". remove it, if your instance of MyObject suppose to be a singleton.

Upvotes: 3

Related Questions