2013-07-11 34 views
1

我正在將一個Web應用程序遷移到Spring 3.2,並享受無需配置web.xml的配置。設置webapprootkey no-web.xml

<context-param> 
<param-name>webAppRootKey</param-name> 
<param-value>webapproot</param-value> 
</context-param> 

我知道,春天創建一個默認的關鍵,但對我來說我跑的多個版本:即剩餘的設置Web應用程序根密鑰,這是我以前在web.xml中沒有像這樣 一部分同樣的戰爭,需要在每個戰爭中設置一個不同的值。所以我最好從屬性文件中獲取一個值並將其用作rootkey。

我想,我會在這裏做到這一點的地方:

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... 

由於任何人誰可以提供建議!

回答

1

第一部分很簡單:

servletContext.setInitParameter("webAppRootKey", getRootKey()); 

,並得到rootkey,在這種情況下被添加到由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; 
} 
+0

你可以分享是在application.properties中,我有一個場景,其中運行兩個webapps,這是從同一個maven快速入門創建的,如果在服務器上的smae時間添加這兩個應用程序會導致問題。這是我的問題:http://stackoverflow.com/q/18543317/1654823,你可以看看 – Venkat