Spring 3.1+でのシンプルな環境サポート

多くの人は、 context:property-placeholderを使用してSpring構成ファイルの値を置換できることを知っています。

<context:property-placeholder location="classpath*:/prop/*.properties"/> <!--    property  --> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg ref="mongo"/> <constructor-arg name="databaseName" value="${mongo.db}"/> <!--       property --> </bean> 

ただし、このアプローチでは、異なるパラメーター値のみを置換できますが、コンテキスト展開のロジックは変更できません。 ただし、場合によっては、外部システムと統合された巨大なシステムを展開する必要があり、場合によっては1つの小さなスタブだけを展開する必要があります。

環境(dev、prod、load-test)に応じて、デプロイメントロジックを変更するタスクに直面したとき、プロパティを介して古い実績のある方法を使用しようとしました。

そして、私は次のことをしました:

my-prod.xmlmy-test.xmlの 2つの異なるコンテキストを作成しましたが、次のようなスイッチャーがあります。

 <context:property-placeholder location="classpath*:/prop/*.properties"/> <import resource="classpath*:my-${proj.env}.xml"/> <!--     property    --> 

しかし、Spring開発者は私の意図を事前に、 かなり前から知っていました

そのため、環境によっては、プロパティを使用してコンテキスト内のさまざまな構成を使用して解決することは不可能です。
Environment 3.1がSpring 3.1に登場していなかった場合、これで話は終わりました。

仕組み
一連のプロファイルを作成し、それらの設定をマークアップするか、これらのインポートスイッチを作成するだけです。

 <beans profile="test"> <!--       "test" --> <import resource="classpath*:/my-test.xml"/> </beans> <beans profile="prod,dev"> <!-- HE       "test" --> <import resource="classpath*:/my-prod.xml"/> </beans> 

起動
2つの起動オプションがあります。

1)コンテキストのインスタンスを通じて:

 ClassPathXmlApplicationContext ontext = new ClassPathXmlApplicationContext(new String[]{"classpath*:bean.xml"}, false); ontext.getEnvironment().setActiveProfiles("test"); ontext.refresh(); 

2)ユニットテスト経由:

 @ContextConfiguration(locations = {"classpath*:bean.xml"}) @ActiveProfiles(profiles = {"test"}) @RunWith(SpringJUnit4ClassRunner.class) public class SuperTest { ... 

はい、すべてがとてもシンプルです;)

PS 英語の記事

Source: https://habr.com/ru/post/J156731/


All Articles