2013-03-18 28 views
1

我有一個使用XML處理所有配置的Spring MVC項目,但是我刪除了所有XML並將它們轉換爲JavaConfig(除Spring Security之外的所有內容)。一旦我嘗試讓Spring Security工作,我可以看到我的項目正在尋找WEB.INF中的applicationContext.xml。我沒有任何指向,所以我需要誰>?爲什麼我的項目需要使用JavaConfig的Spring Security的applicationContext.xml

我secuirty.xml:

<?xml version="1.0" encoding="UTF-8"?> 
<beans:beans xmlns="http://www.springframework.org/schema/security" 
    xmlns:beans="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
         http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 
         http://www.springframework.org/schema/security 
         http://www.springframework.org/schema/security/spring-security-3.1.xsd"> 


    <global-method-security pre-post-annotations="enabled" /> 

    <http use-expressions="true"> 
     <intercept-url access="hasRole('ROLE_VERIFIED_MEMBER')" pattern="/mrequest**" /> 
     <intercept-url pattern='/*' access='permitAll' /> 
     <form-login default-target-url="/visit" /> 

     <logout logout-success-url="/" /> 
    </http> 

    <authentication-manager> 
     <authentication-provider> 
      <user-service> 
       <user name="[email protected]" password="testing" authorities="ROLE_VERIFIED_MEMBER" /> 
      </user-service> 

     </authentication-provider> 
    </authentication-manager> 
</beans:beans> 

這裏是我的webconfig:

@Configuration 
@EnableWebMvc 
@Import(DatabaseConfig.class) 
@ImportResource("/WEB-INF/spring/secuirty.xml") 
public class WebMVCConfig extends WebMvcConfigurerAdapter { 

    private static final String MESSAGE_SOURCE = "/WEB-INF/classes/messages"; 

    private static final Logger logger = LoggerFactory.getLogger(WebMVCConfig.class); 



    @Bean 
    public ViewResolver resolver() { 
     UrlBasedViewResolver url = new UrlBasedViewResolver(); 
     url.setPrefix("/WEB-INF/view/"); 
     url.setViewClass(JstlView.class); 
     url.setSuffix(".jsp"); 
     return url; 
    } 


    @Bean(name = "messageSource") 
    public MessageSource configureMessageSource() { 
     logger.debug("setting up message source"); 
     ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); 
     messageSource.setBasename(MESSAGE_SOURCE); 
     messageSource.setCacheSeconds(5); 
     messageSource.setDefaultEncoding("UTF-8"); 
     return messageSource; 
    } 

    @Bean 
    public LocaleResolver localeResolver() { 
     SessionLocaleResolver lr = new SessionLocaleResolver(); 
     lr.setDefaultLocale(Locale.ENGLISH); 
     return lr; 
    } 

    @Override 
    public void addResourceHandlers(ResourceHandlerRegistry registry) { 
     logger.debug("setting up resource handlers"); 
     registry.addResourceHandler("/resources/").addResourceLocations("/resources/**"); 
    } 

    @Override 
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { 
     logger.debug("configureDefaultServletHandling"); 
     configurer.enable(); 
    } 

    @Override 
    public void addInterceptors(final InterceptorRegistry registry) { 
     registry.addInterceptor(new LocaleChangeInterceptor()); 
    } 

    @Bean 
    public SimpleMappingExceptionResolver simpleMappingExceptionResolver() { 
     SimpleMappingExceptionResolver b = new SimpleMappingExceptionResolver(); 

     Properties mappings = new Properties(); 
     mappings.put("org.springframework.web.servlet.PageNotFound", "p404"); 
     mappings.put("org.springframework.dao.DataAccessException", "dataAccessFailure"); 
     mappings.put("org.springframework.transaction.TransactionException", "dataAccessFailure"); 
     b.setExceptionMappings(mappings); 
     return b; 
    } 

    @Bean 
    public RequestTrackerConfig requestTrackerConfig() 
    { 
     RequestTrackerConfig tr = new RequestTrackerConfig(); 
     tr.setPassword("Waiting#$"); 
     tr.setUrl("https://uftwfrt01-dev.uftmasterad.org/REST/1.0"); 
     tr.setUser("root"); 

     return tr; 
    } 


} 

這裏是我的DatabaseConfig:

@Configuration 
@EnableTransactionManagement 
@ComponentScan(basePackages= "org.uftwf") 
@PropertySource(value = "classpath:application.properties") 
public class DatabaseConfig { 


    private static final Logger logger = LoggerFactory.getLogger(DatabaseConfig.class); 


    @Value("${jdbc.driverClassName}") 
    private String driverClassName; 

    @Value("${jdbc.url}") 
    private String url; 

    @Value("${jdbc.username}") 
    private String username; 

    @Value("${jdbc.password}") 
    private String password; 

    @Value("${hibernate.dialect}") 
    private String hibernateDialect; 

    @Value("${hibernate.show_sql}") 
    private String hibernateShowSql; 

    @Value("${hibernate.hbm2ddl.auto}") 
    private String hibernateHbm2ddlAuto; 

    @Bean 
    public PropertyPlaceholderConfigurer getPropertyPlaceholderConfigurer() 
    { 
     PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer(); 
     ppc.setLocation(new ClassPathResource("application.properties")); 
     ppc.setIgnoreUnresolvablePlaceholders(true); 
     return ppc; 
    } 



    @Bean 
    public DataSource dataSource() { 

     try { 
      Context ctx = new InitialContext(); 
      return (DataSource) ctx.lookup("java:jboss/datasources/mySQLDB"); 
     } 
     catch (Exception e) 
     { 

     } 

     return null; 
    } 

    @Bean 
    public SessionFactory sessionFactory() 
    { 

     LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean(); 
     factoryBean.setDataSource(dataSource()); 
     factoryBean.setHibernateProperties(getHibernateProperties()); 
     factoryBean.setPackagesToScan("org.uftwf.inquiry.model"); 

     try { 
      factoryBean.afterPropertiesSet(); 
     } catch (IOException e) { 
      logger.error(e.getMessage()); 
      e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. 
     } 


     return factoryBean.getObject(); 
    } 

    @Bean 
    public Properties getHibernateProperties() 
    { 
     Properties hibernateProperties = new Properties(); 

     hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect"); 
     hibernateProperties.setProperty("hibernate.show_sql", "true"); 

     hibernateProperties.setProperty("hibernate.format_sql", "true"); 
     hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "update"); 

     hibernateProperties.setProperty("javax.persistence.validation.mode", "none"); 

     //Audit History flags 
     hibernateProperties.setProperty("org.hibernate.envers.store_data_at_delete", "true"); 
     hibernateProperties.setProperty("org.hibernate.envers.global_with_modified_flag", "true"); 

     return hibernateProperties; 
    } 



    @Bean 
    public HibernateTransactionManager hibernateTransactionManager() 
    { 
     HibernateTransactionManager htm = new HibernateTransactionManager(); 
     htm.setSessionFactory(sessionFactory()); 
     htm.afterPropertiesSet(); 
     return htm; 
    } 


} 

和我的web.xml:

<?xml version="1.0" encoding="UTF-8"?> 
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns="http://java.sun.com/xml/ns/javaee" 
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
     id="WebApp_ID" version="2.5"> 


    <display-name>Inquiry</display-name> 
    <welcome-file-list> 
     <welcome-file>index.jsp</welcome-file> 
    </welcome-file-list> 

    <servlet> 
     <servlet-name>Spring MVC Dispatcher Servlet</servlet-name> 
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
     <init-param> 
      <param-name>contextClass</param-name> 
      <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value> 
     </init-param> 
     <init-param> 
      <param-name>contextConfigLocation</param-name> 
      <param-value>org.uftwf.inquiry.config, org.uftwf.inquiry.controller</param-value> 
     </init-param> 
     <load-on-startup>1</load-on-startup> 
    </servlet> 

    <servlet-mapping> 
     <servlet-name>Spring MVC Dispatcher Servlet</servlet-name> 
     <url-pattern>/</url-pattern> 
    </servlet-mapping> 





<filter> 
    <filter-name>springSecurityFilterChain</filter-name> 
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> 
</filter> 
<filter-mapping> 
    <filter-name>springSecurityFilterChain</filter-name> 
    <url-pattern>/*</url-pattern> 
</filter-mapping> 

<listener> 
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
</listener> 

<!-- 


<security-constraint> 
    <web-resource-collection> 
     <web-resource-name>securedapp</web-resource-name> 
     <url-pattern>/*</url-pattern> 
    </web-resource-collection> 

    <user-data-constraint> 
     <transport-guarantee>CONFIDENTIAL</transport-guarantee> 
    </user-data-constraint> 
</security-constraint> 
--> 
</web-app> 

所以我沒有看到任何東西找的applicationContext.xml ....有人可以告訴我爲什麼我需要它來添加它,一旦我做到了開始工作

回答

4

Spring應用程序上下文是分層的。 Web應用程序中的典型安排是,上下文加載器監聽器引導您的AC並使其「全局」可用,然後每個DispatcherServlet都有自己的子應用程序上下文,它可以「看到」所有的Bean(通常是服務,數據源,等等)從上下文加載器監聽器的AC。在所有情況下(當指定ContextLoaderListener或DispatcherServlet時),Spring將自動(基於約定)查找XML應用程序上下文並嘗試加載它。通常你可以通過簡單地指定一個空的contextConfigLocation param(「」)或者告訴它應該期望Java配置類而不是(contextClass屬性)來禁用它。順便說一句,有可能有多個DispatcherServlet。例如,您可能將Spring Integration的入站HTTP適配器與一個,Spring Web Services端點與另一個Spring MVC應用程序以及另一個Spring HTTP調用程序端點一起使用,它們都將通過DispatcherServlet公開。理論上講,你可以使它們在同一個DispatcherServlet中工作,但隔離有助於減少混亂,並且可以共享同一個全局的,更昂貴的bean的單個實例,如DataSources。

+1

你失去了我。你能告訴我在我的例子 – SJS 2013-03-20 14:30:41

+0

我已經在下面添加了一個答案,以幫助顯示你可以禁用Spring尋找一個XML。 – LanceP 2016-12-01 01:42:18

4

您配置在web.xml ContextLoaderListener,但尚未指定contextConfigLocation上下文參數。這種情況下的行爲由該類的javadoc描述:

處理「contextConfigLocation」上下文參數[...]如果未明確指定,則上下文實現應該使用默認位置(with XmlWebApplicationContext:「/WEB-INF/applicationContext.xml」)。

因此,它是ContextLoaderListener需要applicationContext.xml

+0

但爲什麼它尋找它,一旦我添加「@ImportResource」 – SJS 2013-03-18 14:17:06

+1

你沒有讓'ContextLoaderListener'知道你的Spring配置類,所以你怎麼能指望它神奇地知道這些註解?閱讀[javadoc](http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/web/context/ContextLoader。html),並在你的web.xml中包含一個'contextClass'上下文參數(指向你的配置類)。 – zagyi 2013-03-18 14:42:23

+0

此外,感覺就像需要回顧什麼是根Web應用程序上下文(由ContextLoaderListener設置)以及servlet應用程序上下文(由「DispatcherServlet」創建)以及它們之間的關係是什麼。請參閱[本文](http://stackoverflow.com/q/3652090/1276804)以獲得一些快速說明。 – zagyi 2013-03-18 14:52:51

0

爲了確保您的應用程序不使用applicationContext.xml,您可以執行與此類似的操作。你可以看到這一切如何一起here

public class MyInitializer implements WebApplicationInitializer { 

@Override 
public void onStartup(ServletContext servletContext) { 

    //Clear out reference to applicationContext.xml 
    servletContext.setInitParameter("contextConfigLocation", ""); 

    // Create the 'root' Spring application context 
    AnnotationConfigWebApplicationContext rootContext = 
      new AnnotationConfigWebApplicationContext(); 
    rootContext.register(MySpringRootConfiguration.class); 

    // Manage the lifecycle of the root application context 
    servletContext.addListener(new ContextLoaderListener(rootContext)); 

    //Add jersey or any other servlets 
    ServletContainer jerseyServlet = new ServletContainer(new RestApplication()); 
    Dynamic servlet = servletContext.addServlet("jersey-servlet", jerseyServlet); 
    servlet.addMapping("/api/*"); 
    servlet.setLoadOnStartup(1); 
} 
} 
相關問題