Java – Importing resource conditionally in spring application context


Can I import things in a spring context only if a certain condition is met?

<!-- import ONLY IF current environment is NOT testing -->
<import resource="classpath:context/caching-context.xml" />

currently I am doing that by importing a totally different context in my testcases

@ContextConfiguration(locations = { "classpath*:ApplicationContextTesting.xml" })

but maybe there is a more elegant solution to not maintain two separate application contexts for production and testing.

Best Solution

Use Spring profiles.

<beans profile="not_test">
   <import resource="classpath:context/caching-context.xml" />

More information in Spring documentation and on the blog post.