美文网首页
《Spring(5.x)注解驱动开发》bean(二)

《Spring(5.x)注解驱动开发》bean(二)

作者: 曦夫 | 来源:发表于2018-12-25 18:00 被阅读0次

    11.@Value属性赋值

    1. 使用@Value(value="")赋值
    2. 赋值方式
      • 基本数值
           @Value(value = "zhj")
      
      • 使用SpEL:#{}
           @Value("#{3*2}")
      
      • 可以写配置文件[properties]中的值(在运行环境变量里的值):${}
        • 编写bean,properties配置文件
            student.sex=保密
        
        • 为Student(bean)赋值
            public class Student {
                @Value(value = "${student.sex}")
                private String sex;
            }
        
        
        • 将student注入到容器中
            @PropertySource(value = {"classpath:student.properties"},encoding = "UTF-8")
            @Configuration
            public class PropertyValueConfig {
                @Bean
                public Student student(){
                    return new Student();
                }
            }
        

    ps:spring使用@Value标签读取*.properties文件的中文乱码问题的解决


    12.自动装配

    1. spring利用依赖注入(DI),完成对IOC容器中各个组件的依赖关系赋值

    2. @Autowired:自动注入

      • 默认优先按照类型去容器中寻找对应的组件
      • 若注入多个相同类型的bean,再按照组件的属性名作为id查找
      • @Qualifier:按照指定的属性名装配对象
      • @Primary:首选指定某一个bean,优先装配
      • 自动装配一定将属性赋值好,容器中没有该bean无法装配,可以设置装配为非必需。即有则装配 @Autowired(required = false)
    3. spring还支持@Resource(JSR250)和@Inject(JSR330){java规范注解}

      • @Resource:可以和@Autowired一样实现自动装配,默认按照组件名称装配。没有支持@Primary和@Autowired(required = false)功能
      • @Inject:使用该注解需要导入依赖,和@Autowired功能类似,没有非必需功能required = false
          <dependency>
              <groupId>javax.inject</groupId>
              <artifactId>javax.inject</artifactId>
              <version>1</version>
          </dependency>
      
    4. @Autowired:

      • 标注在方法位置上
          1.放在set方法位置
              @Autowired
              public void setBookDao(BookDao bookDao) {
                  this.bookDao = bookDao;
              }
          2.若使用@Bean标注的方法创建对象的时候,方法参数值从容器中取出.@Autowired可以省略。
      
              @Bean
              public BookServiceo(@Autowired BookDao bookDao) {
                    return new BookService();
              }
      
      • 标注在构造器上。默认注入ioc容器中的bean,容器启动会调用无参构造器创建对象,再进行初始化赋值操作。若组件只有一个有参构造器,注解可以省略
          @Autowired
          public  BookService(BookDao bookDao){
              this.bookDao = bookDao;
          }
      
      • 标注在参数上
           public  BookService( @Autowired BookDao bookDao){
                  this.bookDao = bookDao;
           }
      
    5. 若自定义组件使用spring容器底层的一些组件(ApplicationContext,BeanFactory...)

    • 自定义组件(bean)实现相应的XXXAware接口即可。在创建对象的时候,会调用接口规定的方法注入到该组件。
      其中XXXAware使用XXXAwareProcessor后置处理器处理的
       @Component
       public class BeanImplAware implements ApplicationContextAware, BeanNameAware {
    
           private ApplicationContext applicationContext;
    
           @Override
           public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
               this.applicationContext = applicationContext;
           }
    
           //当前bean的名字
           @Override
           public void setBeanName(String name) {
    
           }
       }
    

    6.@Profile环境标识注解

    1. spring为我们提供的可以在根据当前环境,动态的激活和切换一系列的组件的功能
    • 加入环境标识的bean,只有环境被激活的时候才能注册到容器中,默认为default环境
    • 加入环境标识的class,只有在指定环境整个配置类的所有配置才会生效
    • 没有标识的环境注解的bean,任何情况下都生效
    1. eg:若在不同环境下引入不同的数据源生效,引入不同的数据库配置
    • 开发环境/测试环境/生产环境

    • 数据源(dev)/(test)/(prod)

      ①. dbjdbc.properties配置文件

           db.user = root
           db.password = 123
           db.driver = com.mysql.jdbc.Driver
      

      ②. 注入数据库bean,并标识环境

            @PropertySource("classpath:/dbjdbc.properties")
            @Configuration
            public class ProfileConfig implements EmbeddedValueResolverAware {
      
                @Value("${db.user}")
                private String user;
      
                private StringValueResolver driverClass;
      
                private String dirver;
      
                @Override
                public void setEmbeddedValueResolver(StringValueResolver resolver) {
                    this.driverClass = resolver;
                    dirver = driverClass.resolveStringValue("db.driver");
                }
      
                @Profile("default")
                @Bean
                public DataSource dataSourceDev(@Value("${db.password}") String password) throws PropertyVetoException {
                    ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
                    comboPooledDataSource.setUser(user);
                    comboPooledDataSource.setPassword(password);
                    comboPooledDataSource.setJdbcUrl("");
                    comboPooledDataSource.setDriverClass(dirver);
                    return comboPooledDataSource;
                }
      
                @Profile("prod")
                @Bean
                public DataSource dataSourceProd(@Value("${db.password}") String password) throws PropertyVetoException {
                    ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
                    comboPooledDataSource.setUser(user);
                    comboPooledDataSource.setPassword(password);
                    comboPooledDataSource.setJdbcUrl("");
                    comboPooledDataSource.setDriverClass(dirver);
                    return comboPooledDataSource;
                }
      
                @Profile("test")
                @Bean
                public DataSource dataSourceTest(@Value("${db.password}") String password) throws PropertyVetoException {
                    ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
                    comboPooledDataSource.setUser(user);
                    comboPooledDataSource.setPassword(password);
                    comboPooledDataSource.setJdbcUrl("");
                    comboPooledDataSource.setDriverClass(dirver);
                    return comboPooledDataSource;
                }
            }
      
    1. 切换数据源

      • 1.使用命令行的参数:在虚拟机参数位置加载
        -Dspring.profiles.active = test(切换test环境)
      
      • 2.代码的方式激活某个环境
         @Test
         public void test02() {
             //1.创建一个容器
             AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
             //2.设置激活的环境
             applicationContext.getEnvironment().setActiveProfiles("prod","test");
             //3.注册主配置类
             applicationContext.register(ProfileConfig.class);
             //4.启动刷新容器
             applicationContext.refresh();
         }
      

    相关文章

      网友评论

          本文标题:《Spring(5.x)注解驱动开发》bean(二)

          本文链接:https://www.haomeiwen.com/subject/oseflqtx.html