【发布时间】:2015-05-19 13:49:53
【问题描述】:
我正在尝试使用构建配置文件(开发、测试或产品)构建我的项目。我有一个 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} 配置记录器 (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 配置器。
对此的任何帮助表示赞赏。
谢谢。
【问题讨论】:
-
也许不是您问题的答案,但请查看Spring Profiles。使用 Gradle 进行处理和替换感觉不太好。
-
过滤源绝对不是一个好主意。正如@alexvetter 建议的那样,使用弹簧配置文件或过滤资源。
-
感谢您的称赞。我放弃了过滤来源的想法。我从未使用过 Spring Profiles,但它似乎是一个很好的功能。
标签: java spring spring-mvc gradle