spring @Primary @Autowired @Qualifier注解

当spring中管理两个类型一样的bean时,再进行注入时会报错:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.xhx.spring.Spring5AutowiredQualifierApplicationTests': Unsatisfied dependency expressed through field 'user3'; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.xhx.spring.domain.User' available: expected single matching bean but found 2: user1,getUser2

	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:586)
	at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)

看下面代码,@Primary表示当遇到系统中有两个User类型时,优先使用@Primary注解的这个进行注入。

package com.xhx.spring.config;

import com.xhx.spring.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

@Configuration
public class UserConfig {


    @Bean(name = "user1")
    public User getUser1(){
        return new User("a23-fsa-ef","xu",25);
    }

    @Primary
    @Bean(name = "user2")
    public User user2(){
        return new User("brr-dfa-874","haixing",25);
    }



}

看下面测试代码:

package com.xhx.spring;

import com.xhx.spring.domain.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class Spring5AutowiredQualifierApplicationTests {

    @Autowired(required = false)  //一般在开发环境,不确定是否能注入时用
    private User user1;

    @Autowired
    @Qualifier(value = "user1")
    private User user2;

    @Autowired
    private User user3;

    @Test
    public void testAuto() {
        System.out.println(user2.getName());
        System.out.println(user1.getName());
        System.out.println(user3.getName());
    }

}

@Autowired:spring中有两种注入方式,by type/by name,@Autowired使用byType注入,当出现两个类型一样的时候,可以显示的用@Qualifier指定名称,表明用by name方式进行注入。否则会注入@Primary那个类。如果没有指定则会报错。 当不确定系统中是否能注入时,可以使用required=false,不会强制注入。

**实时内容请关注微信公众号,公众号与博客同时更新:程序员星星**

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值