根据名字获取Bean

当Spring IOC容器中有多个相同类型的Bean时,通过注解获取特定Bean会报错。本文介绍了如何使用`@Qualifier`和`@Resource`指定Bean名字来避免冲突,设置主要Bean以确保自动注入特定Bean,以及如何自定义Bean的名称以便按名称查找。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

根据名字获取Bean

当IOC容器中存在多个同类的Bean时,此时如果使用@Autowired注解从容器中获取Bean,会出现异常,因为这是使用匹配类的方式寻找所需要的Bean,而同类的Bean有多个

@Configuration
public class MyConfiguration {

    @Bean
    public Person person1() {
        return new Person(18, "wang");
    }

    @Bean
    public Person person2() {
        return new Person(20, "zhang");
    }
}

此时需要使用指定Bean的名称的方式获取Bean

指定Bean的名字

@Qualifier

在注入的成员变量上使用@Qualifier指定所需的Bean名称,顺利获取Bean,Bean的名称为方法名或@Component注解下的类名

@SpringBootTest
class DemoApplicationTests {

    @Autowired
    @Qualifier("person1")
    Person person;


    @Test
    void contextLoads() {
        System.out.println(person);
    }

}

在这里插入图片描述

@Resource

第二种按Bean名字注入的方式是使用@Resource注解,这是基于Java原生注解的方式注入,可以不使用@Autowired

@SpringBootTest
class DemoApplicationTests {

    @Resource(name = "person1")
    Person person;


    @Test
    void contextLoads() {
        System.out.println(person);
    }

}

@Resource的name属性绑定Bean的名称,同样可以获取Bean,但是注意JDK11版本及以上不支持@Resource,而且使用这种方式,不支持@Primary注解,所以不推荐使用

设置主要Bean

设置主要Bean同样可以解决多个同类型Bean的问题,只需要在其中一个Bean上添加@Primary,Spring在自动注入时便会优先注入这个Bean

@Configuration
public class MyConfiguration {

    @Bean
    @Primary
    public Person person1() {
        return new Person(18, "wang");
    }

    @Bean
    public Person person2() {
        return new Person(20, "zhang");
    }
}

自定义Bean的名称

在Spring中,有时我们需要自定义Bean的名称,而不是使用默认的,这个时候可以使用@Bean的属性来自定义名称

@Configuration
public class MyConfiguration {

    @Bean("wang")
    public Person person() {
        return new Person(18, "wang");
    }
}

此时如果使用匹配Bean名称的方式取出Bean,则需要使用@Bean属性中自定义的属性名

@SpringBootTest
class DemoApplicationTests {

    @Resource(name = "wang")
    Person person;


    @Test
    void contextLoads() {
        System.out.println(person);
    }

}

使用@Component时也一样可以自定义Bean的名称

@Data
@NoArgsConstructor
@AllArgsConstructor
@Component("wang")
public class Person {
    private int age=18;
    private String name;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值