利用Spring Boot作为开发环境,Tomcat部署作为生产环境,由于上下文处理及默认的配置冲突,导致生产环境与开发环境存在较大的差异,不可避免地就要采用@Profile,配置如下:
<beans profile="dev"> <bean class="com.cnitsec.mirana.security.domain.Account"> <property name="username" value="develop"/> </bean> </beans> <beans profile="prod"> <bean class="com.cnitsec.mirana.security.domain.Account"> <property name="username" value="develop"/> </bean> </beans>接着集成ApplicationContextAware接口,激活Profile,代码如下:
@Component public class ApplicationContextInitializer implements ApplicationContextAware { private Account account; private static final Logger logger = LoggerFactory.getLogger(ApplicationContextInitializer.class); /** * @param account */ @Inject public ApplicationContextInitializer(Account account) { super(); this.account = account; } /* (non-Javadoc) * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext) */ @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { Environment env = applicationContext.getEnvironment(); // 只有ConfigurableEnvironment才能激活@Profile if(env instanceof ConfigurableEnvironment) { ConfigurableEnvironment configEnv = (ConfigurableEnvironment)env; configEnv.setActiveProfiles("dev"); } } }但是无法启动,总是提示如下错误:
*************************** APPLICATION FAILED TO START *************************** Description: Parameter 0 of constructor in com.cnitsec.mirana.ApplicationContextInitializer required a bean of type 'com.cnitsec.mirana.security.domain.Account' that could not be found. Action: Consider defining a bean of type 'com.cnitsec.mirana.security.domain.Account' in your configuration.经过一番折腾,找到如下官方示例:
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.getEnvironment().setActiveProfiles("dev"); ctx.register(Account.class); ctx.refresh();我的天,还需要重新注册Java BEAN与刷新整个上下文,更糟糕的是,竟然只有AnnotationConfigApplicationContext才提供了register,叫我这等喜欢基于XML配置的情何以堪?
看来基于程序配置是比较难了,虽然也有基于application.properties的方法,但也只适用于Spring Boot,那就只好修改JVM参数了,右键点击打开“Run Configurations”,在“VM arguments”中输入如下内容
-Dspring.profiles.active="dev"Tomcat配置,与此类似,再次启动,不同的环境激活了不同的配置内容,截图如下。
无论是从性能还是可扩展性来看,在启动参数中激活Spring @Profile都是最优解决方案。