Spring @Profile总是无法激活的解决办法

利用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都是最优解决方案。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值