在spring应用程序上下文中有条件地导入资源

Mat*_*aug 4 java spring

只有满足某个条件,我才能在弹簧环境中导入东西吗?

<!-- import ONLY IF current environment is NOT testing -->
<import resource="classpath:context/caching-context.xml" />
Run Code Online (Sandbox Code Playgroud)

目前我通过在我的测试用例中导入完全不同的上下文来做到这一点

@ContextConfiguration(locations = { "classpath*:ApplicationContextTesting.xml" })
Run Code Online (Sandbox Code Playgroud)

但也许有一个更优雅的解决方案,不能为生产和测试维护两个独立的应用程序上下文.

Grz*_*Żur 8

使用Spring配置文件.

<beans profile="not_test">
   <import resource="classpath:context/caching-context.xml" />
</beans>
Run Code Online (Sandbox Code Playgroud)

有关Spring文档博客文章的更多信息.

  • 这只有在它放在配置文件的末尾才有效,所以之后没有bean定义(Spring 3.2) (2认同)