Spring实战-profile与条件化定义bean

  1. 定义profile
    1.   
      <beans> //root
          <beans profile="dev">
              <bean id=.../>
          </beans>
          <beans profile="qa">
              <bean id=.../>
          </beans>
          <beans profile="prod">
              <bean id=.../>
          </beans>
      </beans>
  2.   激活profile
    1.   spring在确定哪个profile处于激活状态时,需要依赖两个独立的属性:srping.profiles.active 和 spring.profiles.default。其中active属性优先。如果都没有设置,只会创建没有定义在profile中的bean
    2. 设置方法有6个:
      1. 作为DispatcherServlet的初始化参数
      2. 作为Web应用的上下文参数
      3. 作为JNDI条目
      4. 作为环境变量
      5. 作为JVM的系统属性
      6. 在集成测试类上,使用@ActiveProfiles注解设置
    3. 示例
      1.   
        web.xml
        <web-app>
            <context-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>/WEB-INF/config/spring-bean-config.xml</param-value>
            </context-param>
            <context-param>
                <param-name>spring.profiles.default</param-name>
                <param-value>dev</param-value>
            </context-param>
            <listener>
                <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
            </listener>
            <servlet>
                <servlet-name>appservlet</servlet-name>
                <servlet-class>xxx</servlet-class>
                <init-param>
                    <param-name>spring.profiles.default</param-name>
                    <param-value>dev</param-value>
                </init-param>
            </servlet>
        </web-app>
  3. 条件化创建bean
    1. 使用限定符注解@Qualifier
    2. 每个bean,默认有个ID,也默认有个限定符,这两个的默认值“恰巧”都是类名的首字母小写
    3. 创建bean时,使用@Qualifier,装配beans是,还是用@Qualifier

猜你喜欢

转载自www.cnblogs.com/jiangtao1218/p/9691550.html