Is there a CDI @Default equivalent in Spring?

In CDI, I could do this:

// Qualifier annotation @Qualifier @inteface Specific{} interface A {} class DefaultImpl implements A {} @Specific class SpecificImpl implements A {} 

And then in the class:

 @Inject A default; @Inject @Specific A specific; 

It works because the @Default qualifier @Default automatically assigned to injection points without specifying any qualifiers.

But I am working with Spring and have been unable to accomplish this.

 Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException 

The problem is that the default injections (without qualifiers) are already used in a lot of code that I cannot change, and I need to provide another possible implementation of A for my users.

I know that I could add my new implementation under the name bean, but I would like to avoid it.

Is there anything in Spring that could help me with this?

+6
source share
2 answers

Someone pointed out to me that @Primary does just that. I tried and it works great:

 @Primary class DefaultImpl implements A {} 

In my case, DefaultImpl was in xml:

 <bean id="defaultImpl" class="DefaultImpl" primary="true"/> 
+12
source

I could add this as a comment, but I wanted to add formatted code to explain my point of view, and that is why I am adding an explicit answer.

Adding to what you said, you can really use your specific meta annotation inside Spring also in the following lines:

Override @Specific with Spring specific annotation org.springframework.beans.factory.annotation.Qualifier as follows:

 import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Primary; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Qualifier @Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Primary public @interface Specific { } 

I also noted the annotation with the @Primary annotation.

With this in place, your old code should work:

 @Specific class DefaultImpl implements A {} 
0
source

Source: https://habr.com/ru/post/956894/


All Articles