Springでの注記@Profileの使用方法の説明


前言
プロジェクトでMavenを使用して配置をパッケージングする場合、構成パラメータが多すぎる(例えばNginxサーバの情報、ZooKeeperの情報、データベース接続、Redisサーバアドレスなど)ため、実際のネットワークの構成パラメータとテストサーバのパラメータが混同され、配置時にあるパラメータが変更を忘れた場合、配置を再パッケージングしなければならない.これは確かに頭が痛い.そこでSpringのProfileを使って上記の問題を解決し、その使い方を記録して、間違ったところがあったら指摘してください.(感謝).SpringのProfileについて以下の3つの側面から検討する.
SpringのProfileは何ですかProfile を使用する理由
Profile の使用方法
1.SpringのProfileは何ですか.
SpringのProfile機能は、Spring 3.1のバージョンからすでに出ています.Springコンテナで定義されているBeanの論理グループ名として理解できます.これらのProfileがアクティブになっている場合にのみ、Profileで対応するBeanをSpringコンテナに登録することができます.より具体的な例を挙げると、私たちが以前定義したBeanは、Springコンテナが起動すると、これらの情報をすべてロードしてBeanの作成を完了します.Profileを使用すると、Beanの定義をより細かく分割し、これらの定義されたBeanをいくつかの異なるグループに分割します.Springコンテナが構成情報をロードするときは、まずアクティブなProfileを検索し、アクティブなグループで定義されたBean情報だけをロードします.アクティブ化されていないProfileで定義されているBean定義情報は、Beanを作成するためにロードされません.
2.なぜProfileを使うのか
私たちは普段開発中なので、開発時に開発データベースを使用し、テスト時にテストのデータベースを使用し、実際に導入するときにデータベースが必要です.以前の方法は、これらの情報を1つのプロファイルに書くことです.コードをテスト環境に配置すると、プロファイルをテスト環境に変更します.テストが完了すると、プロジェクトは現在のネットワークに配備する必要があります.また、構成情報を現在のネットワークに変更する必要があります.のProfileを使用すると、開発、ユーザーテスト、ユーザー生産の3つのプロファイルをそれぞれ定義できます.これは、それぞれ3つのProfileに対応します.実際に実行する場合、対応するProfileをアクティブにするパラメータを1つ指定するだけで、コンテナはアクティブ化されたプロファイルのみをロードし、構成情報の変更に伴う悩みを大幅に省くことができます.
3.Spring profileの構成
Profileとなぜ使用するのかを説明した後、従来のXMLを使用してBeanのアセンブリを完了する例を示します.
3.1例に必要なMaven依存
簡単なプレゼンテーションを行うだけなので、Springの他のモジュールの内容を導入する必要はなく、コアの4つのモジュール+テストモジュールを導入するだけです.
     <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        
        <spring.version>4.2.4.RELEASEspring.version>
        
        <java.version>1.7java.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-coreartifactId>
            <version>${spring.version}version>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-beansartifactId>
            <version>${spring.version}version>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>${spring.version}version>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-expressionartifactId>
            <version>${spring.version}version>
        dependency>


        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-testartifactId>
            <version>${spring.version}version>
            <scope>testscope>
        dependency>

        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
            <scope>testscope>
        dependency>
    dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-compiler-pluginartifactId>
                <version>2.3.2version>
                <configuration>
                    <source>${java.version}source>
                    <target>${java.version}target>
                configuration>
            plugin>
        plugins>
    build>

3.2例コード
package com.panlingxiao.spring.profile.service;

/**
 *     ,            
 *                        
 */
public interface HelloService {

    public String sayHello();
}

生産環境で使用する実装クラスの定義
package com.panlingxiao.spring.profile.service.produce;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.panlingxiao.spring.profile.service.HelloService;

/**
 *               
 */
@Component
public class ProduceHelloService implements HelloService {

    //               
    @Value("#{config.name}")
    private String name;

    public String sayHello() {
        return String.format("hello,I'm %s,this is a produce environment!",
                name);
    }
}

開発で使用する実装クラスの定義
package com.panlingxiao.spring.profile.service.dev;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.panlingxiao.spring.profile.service.HelloService;

/**
 *            
 */
@Component
public class DevHelloService implements HelloService{

    //                  
    @Value("#{config.name}")
    private String name;

    public String sayHello() {
        return String.format("hello,I'm %s,this is a development environment!", name);
    }

}

Springプロファイルの定義
xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd">

    
    <beans profile="development">
        
        <context:component-scan base-package="com.panlingxiao.spring.profile.service.dev" />
        
        <util:properties id="config" location="classpath:dev/config.properties"/>
    beans>

    
    <beans profile="produce">
        
        <context:component-scan
            base-package="com.panlingxiao.spring.profile.service.produce" />
            
        <util:properties id="config" location="classpath:produce/config.properties"/>
    beans>
beans>

使用するプロファイルの開発、dev/config.properties
    name=Tomcat

本番で使用するプロファイル、produce/config.properties
name=Jetty

テストクラスの作成
package com.panlingxiao.spring.profile.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.panlingxiao.spring.profile.service.HelloService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring-profile.xml")
/*
 *         profile   ,
 *      profile    ,    produce  dev
 */
@ActiveProfiles("produce")
public class TestActiveProfile {

    @Autowired
    private HelloService hs;

    @Test
    public void testProfile() throws Exception {
        String value = hs.sayHello();
        System.out.println(value);
    }
}

dev実行結果をアクティブにします.png
Produce実行結果をアクティブにする.jpg
4.Profileをアクティブにする他の方法
上記では、Profileの使用方法や、ユニットテストの環境で指定したProfileをアクティブにする方法について説明しました.@ActiveProfile注記を使用してprofileをアクティブにするほか、Springでは実際の開発で使用されているものがいくつかあります.Springは、spring.profiles.activeとspring.profiles.defaultの2つの異なるプロパティでアクティブ化できるprofileを決定します.この2つの定数値はSpringのAbstractEnvironmentで定義され、AbstractEnvironmentソースコードを表示します.
    /**
     * Name of property to set to specify active profiles: {@value}. Value may be comma
     * delimited.
     * 

Note that certain shell environments such as Bash disallow the use of the period * character in variable names. Assuming that Spring's {@link SystemEnvironmentPropertySource} * is in use, this property may be specified as an environment variable as * {@code SPRING_PROFILES_ACTIVE}. * @see ConfigurableEnvironment#setActiveProfiles */ public static final String ACTIVE_PROFILES_PROPERTY_NAME = "spring.profiles.active"; /** * Name of property to set to specify profiles active by default: {@value}. Value may * be comma delimited. *

Note that certain shell environments such as Bash disallow the use of the period * character in variable names. Assuming that Spring's {@link SystemEnvironmentPropertySource} * is in use, this property may be specified as an environment variable as * {@code SPRING_PROFILES_DEFAULT}. * @see ConfigurableEnvironment#setDefaultProfiles */ public static final String DEFAULT_PROFILES_PROPERTY_NAME = "spring.profiles.default";


Spring.profiles.activeプロパティが設定されている場合、Springはプロパティ対応値を優先してProfileをアクティブにします.Spring.profiles.activeが設定されていない場合、Springはspring.profiles.defaultプロパティの対応する値に基づいてProfileをアクティブにします.上記の2つのプロパティが設定されていない場合、タスクプロファイルはアクティブ化されず、Profile以外のBeanを定義している場合にのみ作成されます.この2つの属性値はSpringコンテナで定義された属性であり、実際の開発ではSpringコンテナ自体を直接操作することはめったにありません.そのため、この2つの属性を設定するには、特殊な位置を定義し、Springコンテナに自動的にこれらの位置を読み取り、自動的に設定する必要があります.これらの位置は主に以下のように定義されています.
SpringMVCにおけるDispatcherServiceの初期化パラメータとしてのWebアプリケーションコンテキストにおける初期化パラメータとしてのJNDIの入口として環境変数として仮想マシンとしてのシステムパラメータ@AtivceProfileを使用してをアクティブにします.
実際の使用では、デフォルトのprofileを開発環境として定義できます.実際に導入する場合、主は実際に導入した環境サーバでspring.profiles.activeを環境変数に定義してSpringに現在の環境での構成情報を自動的に読み取るようにする必要があります.これにより、異なる環境で頻繁にプロファイルを変更する手間を回避できます.
4.5サンプルコードのダウンロード
サンプルコードダウンロードアドレス:Spring-profile-test
参照先:
Spring Framework Reference Documentation 4.2.5.RELEASE-- 6.13. Environment abstraction
Spring Framework Reference Documentation 3.2.3.RELEASE --3.2 Bean Definition Profiles
<>