我正在尝试使用构建配置文件(dev,test或prod)构建我的项目。我有一个Spring Web应用程序,我正在使用我的WebApplicationInitializer实现初始化。
public class WebMvcInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) {
configureSpringDispacher(servletContext);
configureLogging(servletContext);
}
public void configureSpringDispacher(ServletContext container) {
AnnotationConfigWebApplicationContext context = AnnotationConfigWebApplicationContext();
context.register(WebMvcConfigurer.class);
ServletRegistration.Dynamic dispacher = container.addServlet("dispatcher", new DispatcherServlet(context));
dispacher.setLoadOnStartup(1);
dispacher.addMapping("/");
}
private void configureLogging(ServletContext servletContext) {
servletContext.setInitParameter( "log4jConfigLocation" , "file:/${env}-log4j.properties" );
Log4jConfigListener log4jListener = new Log4jConfigListener();
servletContext.addListener( log4jListener );
}
}
在那里,我尝试使用$ {env}配置logger(log4j),我想用dev-log4j.properties或prod-log4j.properties替换它,具体取决于我构建项目的方式。
在我的build.gradle中,我有:
processResources {
from('src/main/java') {
filter ReplaceTokens, tokens:[
"env": project.getProperty('env')
]
}
}
最后,我正在使用以下方式构建项目:
gradle clean build -Penv = prod
我的占位符$ {env}未被替换。如果我尝试在xml或属性文件中进行过滤,它可以正常工作。我知道日志记录可能不是最重要的配置属性,但我可能也想使用类似的方法来注册特定于环境的Spring配置器。
对此有任何帮助表示赞赏。
感谢。
答案 0 :(得分:0)
我最终过滤了spring.properties文件,然后从我的WebApplicationInitializer中读取它以激活Spring Profile。
这似乎比尝试过滤来源更好。