Spring@主要注释

介绍:

当存在多个相同类型的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
    @Primary
    public Person student() {
        return new Student();
    }
 
    @Bean
    public Person teacher() {
        return new Teacher();
    }
}

TeacherStudent 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 {
   ...
}

现在,当直接尝试插入不带@QualifierPerson类型时,将插入Student bean:

@Service
public class StudentService {
 
    // Student bean is primary and so it'll get injected
    @Autowired
    private Person student;
 
    public void printStudentDetails() {
        System.out.println(student.getClass());
        ...
    }
}

结论:

在本快速教程中,我们探讨了Spring中@Primary批注的用法。

顾名思义,当有多个相同类型的bean时,我们可以使用@Primary批注定义一个主对象。

翻译自: https://www.javacodegeeks.com/2019/10/spring-primary-annotation.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值