当前位置 博文首页 > blackball1998的博客:根据名字获取Bean

    blackball1998的博客:根据名字获取Bean

    作者:[db:作者] 时间:2021-06-20 12:10

    根据名字获取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;
    }
    
    下一篇:没有了