1. 程式人生 > >Spring實戰(四)Spring高級裝配中的bean profile

Spring實戰(四)Spring高級裝配中的bean profile

優先 contex 如何 文件中 web.xml 多個 定義 blog 軟件

  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")註解。

Spring實戰(四)Spring高級裝配中的bean profile