pestrella pestrella - 1 month ago 11
Java Question

What is the correct usage of @Qualifier in Spring?

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.

What is the correct way to use the
@Qualifier
annotation, avoiding the error?

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() {...}

...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