• spring对bean的高级装配之profile机制


      最近在读spring实战一书,个人感觉内容通俗易懂,学到了一些之前并不知道的知识,于是打算在博客里记录一下这些知识点便于后期记忆;

      今天要记录的就是spring的条件化创建bean,针对条件化创建bean方面spring有两方面处理机制,分别是spring3.1引入的profile机制和4.0引入的通过@Conditional注解来定义条件化的bean,下面进行一一介绍.其中例子全部copy书中的案例

      一、profile机制

      书中是通过要创建三个分别适用于开发,生产和qa环境的DataSource来引出条件化bean的 需求并通过profile机制解决的,这里只记录开发、生产两个环境,引入profile之前,我们创建开发和生产的DataSource关键代码如下:

    /*
    *    适用于开发环境的DataSource
    */
    @Bean
    public DataSource dataSource(){
      return new EmbeddedDatabaseBuilder()
                      .addScript("classpath:schema.sql")
                      .addScript("classpath:test-data.sql")
                      .build();
    }      
    
    /*
    *    适用于生产环境的DataSource
    */
    @Bean
    public DataSource dataSource(){
         JndiObjectFactoryBean bean = new JndiObjectFactoryBean ();
        bean.setJndiName('');
        bean.setResourceRef(true);
        bean.setProxyInterfence(java.sql.DataSource.class);
        return (DataSource ) bean.getObject();
    }     

     如果是这样的话每次发布和开发的时候需要更改代码会显得麻烦,所以就需要引入一个机制来让spring知道根据环境的不同来创建合适的bean,下面就需要开始使用profile来完成这一功能.

    首先看下基于java的配置中该如何引入profile

    在Java配置中,可以使用@Profile注解指定某个bean属于哪一个profile.详见代码:

     需要注意的是以上代码的@Profile注解直接用在了方法上,这在spring3.2之前是不允许的,3.2之前只允许作用在类上,这难免会造成代码的冗余,因为每个bean都要给它单独定义一个类来装配profile;

    然后了解一下基于xml配置如何引入profile,直接上代码:

    这样无论是基于java还是xml,都已成功引入profile,那么我们如何激活profile从而让spring知道到底要创建哪个bean呢

    Spring在确定哪个profile处于激活状态时,需要依赖两个独立的属性:spring.profiles.active和spring.profiles.default。
    如果设置了spring.profiles.active属性的话,那么它的值就会用来确定哪个profile是激活的。但如果没有设置spring.profiles.active
    属性的话,那Spring将会查找spring.profiles.default的值。如果spring.profiles.active和spring.profiles.default
    均没有设置的话,那就没有激活的profile,因此只会创建那些没有定义在profile中的bean。

    有多种方式来设置这两个属性:
    作为DispatcherServlet的初始化参数;
    作为Web应用的上下文参数;
    作为JNDI条目;
    作为环境变量;
    作为JVM的系统属性;
    在集成测试类上,使用@ActiveProfiles注解设置。

    下面贴上书中激活profile的代码:

    使用profile进行测试

    当运行集成测试时,通常会希望采用与生产环境(或者是生产环境的部分子集)相同的配置进行测试。但是,如果配置中的bean定义在了profile中,那么在运行测试时,我们就需要有一种方式来启用合适的profile。
    Spring提供了@ActiveProfiles注解,我们可以使用它来指定运行测试时要激活哪个profile。在集成测试时,通常想要激活的是开发环境的profile。例如,下面的测试类片段展现了使用@ActiveProfiles激活dev profile:

     至此spring通过profile来实现条件化创建bean就记录完了,下篇记录如何通过Spring 4.0中提供的@Conditional注解来更高级的条件化创建bean

  • 相关阅读:
    Selenium(一):元素定位
    白盒测试系列(五)条件组合覆盖
    LDAP(轻型目录访问协议)
    Spring Intorduce、History and Design Philosophy
    CORS
    mysql创建用户并授权某个数据库
    Introduce Servlet 、Filter
    web.xml的简单解释以及Hello1中web.xml的简单分析
    ANNOTATION and analyse hello1.java
    Analysis of container and Injection in Java, their history and future.
  • 原文地址:https://www.cnblogs.com/darling2047/p/9553501.html
Copyright © 2020-2023  润新知