zoukankan      html  css  js  c++  java
  • 13、spring注解学习(自动装配)——@Autowired、@Qualifier、@Primary

    自动装配-@Autowired&@Qualifier&@Primary

    • 自动装配:Spring 利用依赖注入(DI),完成对IOC容器中各个依赖关系赋值

    @Autowired :自动注入

    • 默认优先按照类型去容器中找对应的组件,applicationContext.getBean(BookRepository.class),找到就赋值。
    • 如果找到多个相同类型的组件,再将属性名称作为组件的id 去容器中查找applicationContext.getBean("bookRepository")
    • 使用 @Qualifier("bookRepository") 指定装配组件
    • 自动装配默认一定要将属性赋值好,没有就会报错。可以使用@Autowired(required = false)来配置非必须的注入,有则注入,没有就算了。
    • @Primary 让Spring进行自动装配的时候,默认选择需要装配的bean,也可以继续使用@Qualifier 指定需要装配的bean的名称
    • @Qualifier 的权重大于 @Primary,如果指定了@Qualifier 则 @Primary失效

    代码实例

      1、spring主配置类

    import javax.management.relation.RelationType;
    
    /**
     * Spring 利用依赖注入(DI),完成对IOC容器中各个依赖关系赋值
     * 1. @Autowire
     */
    @Configuration
    @ComponentScan({"com.hw.springannotation.service", "com.hw.springannotation.controller", "com.hw.springannotation.dao"})
    public class MainConfigOfAutowired {
    
        @Primary // 首选装配bean
        @Bean("bookRepository2")
        public BookRepository bookRepository() {
            return new BookRepository("2");
        }
    }

      2、BookService

    @Service
    public class BookService {
    
        @Autowired(required = false)
        // @Qualifier("bookRepository")
        private BookRepository bookRepository2;
    
        public void print() {
            System.out.println("bookRepository2。。。");
        }
    
        @Override
        public String toString() {
            return "BookService{" +
                    "bookRepository=" + bookRepository2 +
                    '}';
        }
    }

      3、测试方法

    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfAutowired.class);
    
    @Test
    public void test1() {
        BookService bookService = applicationContext.getBean(BookService.class);
        System.out.println(bookService);
    
        applicationContext.close();
    }

    测试结果

  • 相关阅读:
    hugo博客使用 utterances 作为评论系统
    使用DEM生成彩色的立体图像
    hibernate Annotation 注解形式 实例 事务 hibernate.cfg.xml
    web.xml配置webAppRootKey 的问题
    JAVA 生成二维码 代码
    关于Boost库的split函数在不同的编译器下的使用
    纯 hibernate hibernate.cfg.xml 事务 数据库操作 CRUD
    Android 百度地图API 定位 导航 代码
    Android GPS
    使用GDAL对DEM进行彩色渲染
  • 原文地址:https://www.cnblogs.com/lyh233/p/12449381.html
Copyright © 2011-2022 走看看