0

在我的web應用程序中,我創建了一個從AbstractAnnotationConfigDispatcherServletInitializer擴展的CustomWebApplicationInitializer。 我需要爲應用程序添加另一個屬性源。我通過在servletContext中設置InitParameter來實現onStartup方法。Spring web應用上下文

public class MvcWebApplicationInitializer extends 
     AbstractAnnotationConfigDispatcherServletInitializer { 
    private static final String[] SERVLET_MAPPINGS = new String[] {"/"}; 
    private static final String SESSION_COOKIE_PATH = "/"; 

    @Override 
    protected Class<?>[] getRootConfigClasses() { 
     return new Class[] {AppConfig.class}; 
    } 

    @Override 
    protected Class<?>[] getServletConfigClasses() { 
     return new Class[] {WebConfig.class}; 
    } 

    @Override 
    protected String[] getServletMappings() { 
     return SERVLET_MAPPINGS; 
    } 


    @Override 
    public void onStartup(ServletContext servletContext) throws ServletException { 
     super.onStartup(servletContext); 
     servletContext.setInitParameter("contextInitializerClasses", "com.test.myproject.MyTestPropertySourceInitializer"); 
    } 
    } 

如果特定屬性的值被設置爲true MyTestPropertySourceInitializer實現ApplicationContextInitializer和檢查。

public void initialize(ConfigurableApplicationContext applicationContext) { 
    ConfigurableEnvironment env = applicationContext.getEnvironment(); 
    Boolean testPropEnabled = (Boolean) env.getProperty("testProperty.enabled", Boolean.class); 

我已經將該屬性值設置爲true。但是在日誌中,值是錯誤的,並且不按預期處理。所以我認爲在調用initialize方法的時候,屬性文件不會被加載到applicationContext中。 請告訴我如何得到這個工作。提前致謝。

回答

0

嘗試,用武力裝入特性文件

public void initialize(ConfigurableApplicationContext applicationContext) { 
    ConfigurableEnvironment env = applicationContext.getEnvironment(); 
    env.getPropertySources().addFirst(new ResourcePropertySource("classpath:application.properties")) 

    Boolean testPropEnabled = (Boolean) env.getProperty("testProperty.enabled", Boolean.class); 

} 
+0

很抱歉的混亂描述。初始化方法在另一個通用庫中,許多其他項目正在使用這個庫,這就是爲什麼我們無法在那裏進行強制加載的原因。在調用servletcontext setInitParameter方法之前,我會嘗試在我的項目中強制加載,並讓你知道這是否可行。 – NewQueries

相關問題