我正在将一个 Web 应用程序迁移到 Spring 3.2,并且正在享受无 web.xml 的配置。 剩下的一部分是设置 webapp 根 key ,我之前在 web.xml 中这样做过,如下所示:
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>webapproot</param-value>
</context-param>
我知道 Spring 创建了一个默认 key ,但就我而言,我正在运行同一 war 的多个版本,并且需要在每个版本中将 key 设置为不同的值。因此,最好我想从属性文件中获取一个值并将其用作根键。
我想我会在这里的某个地方这样做:
public class WebAppInitializer implements WebApplicationInitializer {
private static final Logger logger = Logger.getLogger(WebAppInitializer.class);
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
// Create the root appcontext
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(AppConfig.class);
servletContext.addListener(new WebAppRootListener());
// Manage the lifecycle of the root appcontext
servletContext.addListener(new ContextLoaderListener(rootContext));
//servletContext.setInitParameter("defaultHtmlEscape", "true");
// The main Spring MVC servlet.
ServletRegistration.Dynamic springapp = servletContext.addServlet(
"springapp", new DispatcherServlet(rootContext));
springapp.setLoadOnStartup(1);
Set<String> mappingConflicts = springapp.addMapping("/");
...etc...
感谢任何可以提供建议的人!
最佳答案
第一部分很简单:
servletContext.setInitParameter("webAppRootKey", getRootKey());
并获取根 key ,在本例中,该根 key 由 Maven 构建添加到 application.properties 文件中,
private String getRootKey() {
Properties prop = new Properties();
ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream stream = loader.getResourceAsStream("application.properties");
String key=null;
try {
prop.load(stream);
key = prop.getProperty("rootKey");
} catch (Exception e) {
throw new RuntimeException("Cannot load webapprootkey", e);
}
return key;
}
关于java - 设置 webapprootkey no-web.xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17588635/