Using Spring 3.X.X I have 2 services annotated with @Primary and I created another configuration class where I want to use a "customised" version of one of the services.
For some reason I ignore while debugging the configuration class I see that it gets the correct dependencies but when I want to use it it has setup the wrong ones.
I find it easier to explain with code, here is an example:
Interface Foo:
public interface Foo {
String getMessage();
}
Primary implementation with a default message hardcoded:
@Primary
@Service("FooImpl")
public class FooImpl implements Foo {
private String message = "fooDefaultMessage";
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
Bar interface:
public interface Bar {
void doBar();
}
Bar default implementation:
@Primary
@Service("BarImpl")
public class BarImpl implements Bar {
private Foo foo;
@Override
public void doBar() {
System.out.println(foo.getMessage());
}
public Foo getFoo() {
return foo;
}
@Autowired
public void setFoo(Foo foo) {
this.foo = foo;
}
}
So far so good, if I want to Inject a Bar I get everything as expected. Thing is I have a Configuration with the following:
@Configuration
public class BeanConfiguration {
@Bean
@Qualifier("readOnlyFoo")
Foo readOnlyFoo() {
FooImpl foo = new FooImpl();
foo.setMessage("a read only message");
return foo;
}
@Bean
@Qualifier("readOnlyBar")
Bar readOnlyBar() {
BarImpl bar = new BarImpl();
bar.setFoo(readOnlyFoo());
return bar;
}
}
When I want to inject a readOnlyBar I am getting the default Foo instead of the one set up here.
private Bar readOnlyBar;
@Autowired
@Qualifier("readOnlyBar")
public void setReadOnlyBar(Bar readOnlyBar) {
this.readOnlyBar = readOnlyBar;
}
...
readOnlyBar.doBar();
Has the Foo bean with "fooDefaultMessage". Why is that? How can I make sure Spring uses the Bean I set on the @Configuration?
Thanks in advance,
EDIT: Note that the same happens if instead of calling the readOnly() method in the @Configuration class you pass a @Qualified argument. i.e.:
@Configuration
public class BeanConfiguration {
@Bean
@Qualifier("readOnlyFoo")
Foo readOnlyFoo() {
FooImpl foo = new FooImpl();
foo.setMessage("a read only message");
return foo;
}
@Bean
@Qualifier("readOnlyBar")
Bar readOnlyBar(@Qualifier("readOnlyFoo") Foo readOnlyFoo) {
BarImpl bar = new BarImpl();
bar.setFoo(readOnlyFoo);
return bar;
}
}
If instead I try using Constructor dependency injection everything works as I want/expect but unfortunately I can't use that.