user3557214
user3557214

Reputation: 91

Custom Annotations in spring

In my project we have set up something like below


    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD,ElementType.ANNOTATION_TYPE, ElementType.PARAMETER})
    @Inherited
    @Documented
    @Qualifier(“MessageConverterQualifier”)
    public @interface MessageConverterRef {}

Above Is used at many places in CoreConfig files (annotation based loading)


    @Bean
    @MessageConverterRef
    public DocumentToABCResponseMessageConverter 
      documentToABCResponseMessageConverter() {

    return new DocumentToABCResponseMessageConverter();
    }
    @Bean
    @MessageConverterRef
    public StringToABCResponseMessageConverter stringToABCResponseMessageConverter(
    StringToDomBasedMessageConverter stringToDomBasedMessageConverter) {
    return new StringToABCResponseMessageConverter(stringToDomBasedMessageConverter);
    }

I am not able to understand what is the need of MessageConvertoerRef custom annotation here. This custom annotation is used at now of places while initializing the beans using @Bean.

Request you to let me know what does it mean and what difference is it making .

Upvotes: 1

Views: 370

Answers (1)

Gergely Bacso
Gergely Bacso

Reputation: 14661

This is an elegant solution to ensure compile-time safety for autowiring a set of beans by using the same qualifier. If you look at your custom annotation @MessageConverterRef you will see that the only truly meaningful annotation it is decorated with is:

@Qualifier(“MessageConverterQualifier”))

Use case: you happen to have a set of beans serving the same purpose (like having converters for different types, like you do) it would be really convinient to annotate all of them with the same Spring Qualifier (in your case MessageConverterQualifier), so that they can be all autowired into a list.

The next step is to recognize that having a set of beans scattered across your project that should be annotated with the same qualifier name is not enterily safe, neither the most elegant solution. Defining your own annotation (@MessageConverterRef) once, and reuse it everywhere it is needed reduces the chance of of error (typos) and at the same time increases readability and provides a cleaner code.

For more info on the topic I suggest reading the corresponding Spring doc, especially this part:

Qualifiers also apply to typed collections (as discussed above): e.g. to Set. In such a case, all matching beans according to the declared qualifiers are going to be injected as a collection. This implies that qualifiers do not have to be unique; they rather simply constitute filtering criteria. For example, there could be multiple MovieCatalog beans defined with the same qualifier value "action"; all of which would be injected into a Set annotated with @Qualifier("action").

Upvotes: 1

Related Questions