Spring实战(四)Spring高级装配中的bean profile

时间:2023-03-09 16:40:27
Spring实战(四)Spring高级装配中的bean profile

  profile的原意为轮廓、剖面等,软件开发中可以译为“配置”。

  在3.1版本中,Spring引入了bean profile的功能。要使用profile,首先要将所有不同的bean定义整理到一个或多个profile中,在将应用部署到每个环境时,要确保对应的profile处于激活(active)状态。

  1、@Profile注解应用在类上

  在一个类上使用JavaConfig中的注解@Profile("xxx"),指定这个类中的bean属于某一个profile。

  它告诉Spring,这个配置类中的bean只有在xxx profile激活时才会创建;

  如果xxx profile没有被激活,那类中的@Bean注解的方法都会被忽略。

  2、@Profile注解应用在方法上

  Spring3.2开始,可以在方法级别上使用@Profile注解,与@Bean注解一起使用。

  这样做的一个好处是,可以将不同的bean(所属的profile也不同)的声明,放在同一个配置类(@Configuration)中。

  只有当指定的profile被激活时,相应的bean才会被创建。

  而没有指定profile的bean,始终都会被创建。

  @Configuration

  public class AConfigClass{

    @Bean

    @Profile("A")

    methodA(){...};

    @Bean

    @Profile("B")

    methodB(){...};
  }

  3、XML中配置多个profile

  以下<beans>元素嵌套在root <beans>中,这样也可以在一个XML文件中配置多个profile。

<beans profile="dev">
...
...
</beans>

  4、如何激活某个profile?

  Spring在确定某个profile是否被激活时,依赖两个独立的属性:

  A---spring.profiles.active

  B---spring.profiles.default

  如果设置了A属性,它的值会优先被Spring用来确定哪个profile是激活的;

  如果没有,Spring会查找B的值;

  若A、B均没有设置,则没有激活的profile,Spring则只会创建没有定义在profile中的bean。

  5、怎样设置上述A、B属性的值呢?

  作者最喜欢的一种方式是使用DispatcherServlet的参数将spring.profiles.default设置为开发环境的profile,这样所有的开发人员都可以从版本控制软件中获得应用程序源码。

  web.xml(web应用程序中)

<context-param>
<param-name>spring.profiles.default</param-name>
<param-value>dev</param-value>
</context-param>

  6、测试时,激活相关的profile,Spring提供了@ActiveProfiles("dev")注解指定它在运行测试时激活。