为AbstractAnnotationConfigDispatcherServletInitializer设置一个可以与@PropertySource一起使用的活动配置文件?

 忧郁王囝 发布于 2023-02-10 09:39

我正在使用AbstractAnnotationConfigDispatcherServletInitializer配置我的Web应用程序.我还有一个@Configuration用于创建几个bean的类.在这个类中,我使用@PropertySource注释来加载各种设置的属性文件(例如数据库连接细节).

目前,我使用Maven配置文件和Ant任务为我的运行时环境创建正确的属性文件.也就是说,我让Maven在构建时将"prod.properties"或"dev.properties"移动到"application.properties"(该类使用).我想要做的是使用Spring配置文件来消除这种情况.我希望能够做到以下几点:

@PropertySource( value = "classpath:/application-${spring.profiles.active}.properties")

我还想在不使用任何XML的情况下设置配置文件.所以我需要根据系统属性的存在来设置配置文件.例如,

String currentEnvironment = systemProperties.getProperty("current.environment");
if (currentEnvironment == null) {
  ((ConfigurableEnvironment)context.getEnvironment()).setActiveProfiles("production");
} else {
  ((ConfigurableEnvironment)context.getEnvironment()).setActiveProfiles(currentEnvironment);
}

不过,我不知道我能在哪里做到这一点.根据相关问题的答案,可以createRootApplicationContext在我的初始化器类中重写该方法.但是,该答案还依赖于在设置配置文件之前加载的配置类.

我想做什么?如果是这样,怎么样?

1 个回答
  • 压倒createRootApplicationContextcreateServletApplicationContext不为我工作.我遇到了各种错误,例如非法状态异常和"$ {spring.profiles.active}"无法解析.通过继承树挖掘AbstractAnnotationConfigDispatcherServletInitializer我设计了以下解决方案:

    public class ApplicationInitializer
      extends AbstractAnnotationConfigDispatcherServletInitializer
    {
      @Override
      public void onStartup(ServletContext context) throws ServletException {
        super.onStartup(context);
    
        String activeProfile = System.getProperty("your.profile.property");
        if (activeProfile == null) {
          activeProfile = "prod"; // or whatever you want the default to be
        }
    
        context.setInitParameter("spring.profiles.active", activeProfile);
      }
    }
    

    现在您可以创建如下所示的配置类,它可以正常工作:

    @Configuration
    @PropertySource( value = "classpath:application-${spring.profiles.active}.properties" )
    public class MyAppBeans {
      @Autowired
      private Environment env;
    
      @Bean
      public Object coolBean() {
        String initParam = this.env.getProperty("cool.bean.initParam");
        ...
        return coolBean;
      }
    }
    

    当然,您可以通过VM选项(-Dyour.profile.property=dev)或容器属性(例如Tomcat容器属性)设置"your.profile.property" .

    2023-02-10 09:43 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有