java - 设置 webapprootkey no-web.xml

标签 java spring-mvc

我正在将一个 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/

相关文章:

java - AVL树: solving a StackOverflowError

java - 需要帮助创建适用于 Android 的测验应用程序 w。 HashMap 和无数据库

java - 隐藏 Jackson 序列化中的 protected 字段

java - 依赖注入(inject)是如何手动实现的?

java - Spring Boot 和 AngularJS

java - 数据未持久保存到数据库并在控制台中显示空指针异常

org/springframework/aop/framework/AbstractAdvisingBeanPostProcessor 的 java.lang.NoClassDefFoundError

java - 为面板制作背景图像时遇到问题

java - 在Java Controller 上如何获取注释@RequestMapping ("/getThisValueFromOtherClass")的值?

java - 信息 : No Spring WebApplicationInitializer types detected on classpath (jre 1. 8)