I currently in the process of learning Spring, and have a multi module maven project (parent pom, several poms beneath etc.) and as many context files.

I am now looking to use two different Spring profiles for two different environments, A and B.

All of the bean definitions will remain the same, however the values pulled in from .properties files will vary.

If I am reading the documentation correctly I have to duplicate each of my context.xml files, and set one as profileA with the properties file for A, and the other set as profileB with the properties file for B being brought in.

Is this the correct implementation? It seems to make sense if bean signatures change, but if they are exactly the same and only the property values being pulled in vary there seems like there should be an easier way. I want to do this at runtime so I only have to build once, which is why I have decided against maven profiles.

Thanks

有帮助吗?

解决方案

There is no need to duplicate your context.xml. What you need is to make spring you different properties based on the supplied profile. This can be done either with XML or Java Config easily. If you are using XML, then at the end of your context.xml, you need to do something like this

<beans profile="dev">
     <context:property-placeholder location="classpath*:dev.properties"/>
</beans>
<beans profile="production">
     <context:property-placeholder location="classpath*:production.properties"/>
</beans>

If you need the corresponding Java Config, let me know and I will post that for you.

When you start the application you need to supply the correct profile (one way is by adding -Dspring.profiles.active="production" to the command line arguments)

Also I would recommend that if you are just getting started with project, check out Spring Boot which greatly simplifies Spring configuration (and takes case of what you want in an even easier way)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top