pestrella pestrella - 22 days ago 4
Java Question

Could not autowire using method-level annotation @Qualifier in IntelliJ

I've seen code like the following:

@Bean
@Qualifier("fooService")
public Foo fooService(Env env) {
return new Foo(env);
}

@Bean
public Bar barService(@Qualifier("fooService") Foo foo) {
return Bar(foo);
}


IntelliJ marks this wiring an error, specifically line 2, with the following error:

Could not autowire. Qualified bean must be of 'Env' type


However, the program starts up fine.

Why is this an autowiring error?

UPDATE: it turns out that this is an IntelliJ issue, and that the above is valid according to Spring documentation. The clue that points to this being an IntelliJ issue is the error message; it seems to suggest that the
@Qualifier
annotation is attached to the
Env
argument, which it's not. I tested this with IntelliJ 15.0.6, and appears to be fixed in 2016.2.1.

Answer

From the @Qualifier Javadoc...

This annotation may be used on a field or parameter as a qualifier for candidate beans when autowiring. It may also be used to annotate other custom annotations that can then in turn be used as qualifiers.

By default, Spring autowires "by name", not "by type". So, if you have...

@Bean public Object myObject() {...}

...the implicit name of the bean would be "myObject" and you would autowire it as a collaborator like this...

@Autowire Object myObject

However, if you want to name your bean something different...

@Bean(name="foo") public Object myObject() {...}

You could rename your collaborator...

@Autowire Object foo

Or you could use @Qualifier...

@Qualifier("foo") @Autowire Object myObject

Comments