我正在使用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
在我的初始化器类中重写该方法.但是,该答案还依赖于在设置配置文件之前加载的配置类.
我想做什么?如果是这样,怎么样?
压倒createRootApplicationContext
或createServletApplicationContext
不为我工作.我遇到了各种错误,例如非法状态异常和"$ {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" .