preface
When there are multiple implementations of an interface, we can inject the beans we want by giving the @AutoWired annotation with @Qualifier. Here’s another case: Beans are prioritized, and generally we just inject the default implementation; In this case, you can use the @primary annotation, which is annotated on the Bean to indicate which class is injected first.
The source code
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Primary {
}
Copy the code
use
When used, annotate directly on the method that returns the Bean
.@Autowired
private MyBean myBean(a); / / injection myBean1
@Primary
@Bean
public MyBean myBean1(a) {
return new MyBean();
}
@Bean
public MyBean myBean2(a) {
return newMyBean(); }...Copy the code
You can also tag @Component classes (@controller, @Service, @repository)
@Primary
@Component
public class MyBean {
/ /...
}
Copy the code