Custom Qualifier with @Bean annotation
In this post under Spring Core, I will show with example how to create a custom qualifier and use it with “@Bean” annotation.
For our example, I will create a “@DaoGenre” custom qualifier as shown below
Custom Qualifer
package core.package46;
import org.springframework.beans.factory.annotation.Qualifier;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface DaoGenre {
String value();
}
As you can see in the above code, we created a custom qualifier and marked it with “@Qualifer” annotation.
The “DaoGenre” has only property named “value”.
Next I will show you how to user it.
I will create an class named “Dao” as shown below
Dao
package core.package46;
public class Dao {
private String daoName;
public Dao(String daoName) {
this.daoName = daoName;
}
@Override
public String toString() {
return this.daoName;
}
}
Next I will show how to use “@Qualifier” with “@Bean” annotation.
Below is the main class for your reference
Main class
package core.package46;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "core.package46")
public class Example46 {
@Autowired
@DaoGenre("db")
private Dao dao;
@Bean
@DaoGenre("jms")
public Dao jmsDao() {
return new Dao("jmsDao");
}
@Bean
@DaoGenre("db")
public Dao dbDao() {
return new Dao("dbDao");
}
public Dao getDao() {
return this.dao;
}
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example46.class);
Example46 example = applicationContext.getBean(Example46.class);
System.out.println(example.getDao());
}
}
In the above main code, I created two bean definitions “dbDao” and “jmsDao”.
Annotated them with “@DaoGenre” annotation, with the value “db” for “dbDao” bean and “jms” for “jmsDao”.
Now at line 16, I created a private field “dao” to which one of the beans “dbDao” or “jmsDao” must be assigned.
Spring cannot figure out which bean should be assigned in this case.
So to help Spring framework, we assigned “DaoGenre” custom qualifier with the name “db” as as agrument to “@DaoGenre” annotation. Refer to line 15.
As a result of which Spring framework creates a bean of “dbDao” and assign it to “dao” field.
In this way we can use “@Qualifier” with “@Bean” annotation.