销售类网站数据库的建设,怎样在手机上网站建设,2018年的网站制作,什么是seo和sem有什么区别介绍#xff1a; 当存在多个相同类型的bean时#xff0c;使用Spring Primary批注为标记的bean提供更高的优先级。 默认情况下#xff0c;Spring按类型自动连线。 因此#xff0c;当Spring尝试自动装配并且有多个相同类型的bean时#xff0c;我们将获得NoUniqueBeanDefini… 介绍 当存在多个相同类型的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 {BeanPrimarypublic 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(basePackagescom.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 itll get injectedAutowiredprivate Person student;public void printStudentDetails() {System.out.println(student.getClass());...}
}结论 在本快速教程中我们探讨了Spring中Primary批注的用法。 顾名思义当有多个相同类型的bean时我们可以使用Primary批注定义一个主对象。 翻译自: https://www.javacodegeeks.com/2019/10/spring-primary-annotation.html