@Qualifier and autowired
We can label the bean given a @Qualifier to it in several ways. take the examples below
@Service
public class RecordsService {
//(1º)
@Autowired
@Qualifier("dbItemsProcessor")
private ItemsProcessor recordsProcessor;
//(2º)
@Autowired
@Qualifier("file-items-reader")
private ItemsReader recordsReader;
//(3º)
@Autowired
@Qualifier("db-writer")
private ItemsWriter recordsWriter;
//(4º)
@Autowired
@ItemValidatorType(FILE)
private ItemsValidator recordsValidator;
}
1 - Automatic bean generated by spring
The first @Autowired is related to the automatic generated bean name by spring. If you do not define any bean @Qualifier spring automatic generates the name based on the name of the class.
2 - @Component name
Second example is naming your component like below:
@Component("items-reader")
public class ItemsReader {}
3 - @Qualifier in the class
3rd example is using the @Qualifier in the class
@Component
@Qualifier("db-writer")
public class ItemWriter {}
4 - Custom annotation
4th example is using your custom annotation , which you can see also extends @Qualifier and has a enum of 2 possible values.
@Qualifier
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ItemValidatorType {
ItemValidatorType value();
enum RecordsValidatorMode {
DB,
FILE
}
}