Hello,
First of all thanks for this magnificent framework.
Now let's get to the point with a sample. Let's say we have 3 interfaces First, Second and Third like below:
public interface First {}
public interface Second extends First {}
public interface Third extends Second {}
And, at least for now, two implementations like below:
@Component
@Primary
public class FirstImpl implements First {}
@Component
public class SecondImpl implements Second {}
Everything is perfect, i can bind both interfaces with their implementations :
public SomeConstructor(First first) {} // OK, it works
public SomeOtherConstructor(Second second) {} // OK, it works
But here comes the Third implementation :
@Component
public class ThirdImpl implements Third {}
And now the pain that may force us to fall back to qualifiers:
public SomeConstructor(First first) {} // OK, it works
public SomeOtherConstructor(Second second) {} // KO, NoUniqueBeanDefinitionException,Third is a Second
public SomeOtherOtherConstructor(Third third) {} // OK, it works
To solve this issue i would like to allow @Primary annotation to specify on which class or interface it applies then we could use it as follow:
@Component
@Primary
public class FirstImpl implements First {}
@Component
@Primary(for = {Second.class})
public class SecondImpl implements Second {}
@Component
@Primary(for = {Third.class})
public class ThirdImpl implements Third {}
Another use case would be to select primary interfaces on the same bean like:
@Component
@Primary(for = {Interface1.class, Interface3.class})
public class SomeImpl implements Interface1,Interface2,Interface3 {}
I hope it makes sense for who will read it
Comment From: snicoll
Thanks for the suggestion but we're not keen in making the annotation model more complex. There are some discussions about adding a fallback, see #26241 that would be quite difficult to implement if the scope of @Primary
was extended.
Besides the core container doesn't have a notion of restricted type. The visible type in the bean factory is a candidate for injection in general so the kind of restriction that you're alluding would break with regular @Bean
semantic. Qualifiers are probably a good candidate for the use case above.