介绍:
当存在多个相同类型的bean时,使用Spring @Primary批注为标记的bean提供更高的优先级。
默认情况下,Spring按类型自动连线。 因此,当Spring尝试自动装配并且有多个相同类型的bean时,我们将获得NoUniqueBeanDefinitionException :
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.programmergirl.Person]is defined: expected single matching bean but found 2: student, teacher
...
为了解决这个问题,我们可以选择使用Spring @Primary批注,从而将一个bean标记为主豆。
在本教程中,我们将更详细地探讨此批注的用法。
假设我们有以下配置类:
@Configuration
public class UniversityConfig {@Bean@Primarypublic Person student() {return new Student();}@Beanpublic Person teacher() {return new Teacher();}
}
Teacher和Student Bean都继承自Person ,因此我们将其标记为两个@Bean注释方法的返回类型。
但是,请注意, 我们已使用@Primary批注将Student bean标记为主要bean。 现在,让我们启动我们的应用程序:
AnnotationConfigApplicationContext context =AnnotationConfigApplicationContext(UniversityConfig.class);Person student = context.getBean(Person.class);
System.out.println(student.getClass());
我们将看到Spring尝试自动装配时,一个Student对象得到了优先选择。
使用
假设我们启用了组件扫描:
@Configuration
@ComponentScan(basePackages="com.programmergirl.beans")
public class UniversityConfig {
}
对于这种情况, 我们可以使用@Primary直接注释我们的Spring组件类:
@Primary
@Component
public class Student implements Person {...
}@Component
public class Teacher implements Person {...
}
现在,当直接尝试插入不带@Qualifier的Person类型时,将插入Student bean:
@Service
public class StudentService {// Student bean is primary and so it'll get injected@Autowiredprivate Person student;public void printStudentDetails() {System.out.println(student.getClass());...}
}
结论:
在本快速教程中,我们探讨了Spring中@Primary批注的用法。
顾名思义,当有多个相同类型的bean时,我们可以使用@Primary批注定义一个主对象。
翻译自: https://www.javacodegeeks.com/2019/10/spring-primary-annotation.html