📜 ⬆️ ⬇️

Simple support for environments in Spring 3.1+

Many people know that you can use context: property-placeholder to substitute values ​​into Spring configuration files.

<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> 

But, with this approach, you can only substitute different values ​​of the parameters, but not change the logic of the context deployment. But in some cases, we need to deploy a huge system that is integrated with external systems, and in some cases - just one small stub.

When a task arose before me, depending on the environment (dev, prod, load-test), to change the deployment logic - I sincerely tried to use the old proven method through property.

And I did the following:
')
I created 2 different contexts: my-prod.xml and my-test.xml and here’s the switch:

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

But the Spring developers knew about my intention in advance, much in advance .

So, using property to confuse using different configs in context, depending on the environment, is impossible.
At this point one could finish the story if there were no Environment 's in Spring 3.1.

How it works :
You just need to come up with a set of profiles and mark their configs with them, or make these import switches like this:

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

Run :
There are two startup options:

1) Through an instance of context:

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

2) Through the unit test:

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

Yes, everything is so simple;)

Ps English article

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


All Articles