1

我有一个 Spring MVC 项目,它使用 XML 进行所有配置,但我删除了所有 XML 并将它们放入 JavaConfig(除 Spring Security 之外的所有内容)。一旦我尝试让 Spring Security 工作,我可以看到我的项目正在爆炸中寻找 WEB.INF 中的 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="cpilling04@aol.com.dev" password="testing" authorities="ROLE_VERIFIED_MEMBER" />
            </user-service>

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

这是我的网络配置:

@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;
    }


}

这是我的数据库配置:

@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

3 回答 3

4

ContextLoaderListener在 web.xml 中进行了配置,但尚未指定contextConfigLocation上下文参数。这种情况下的行为由该类的 javadoc 描述:

处理“contextConfigLocation”上下文参数 [...] 如果没有明确指定,上下文实现应该使用默认位置(使用 XmlWebApplicationContext:“/WEB-INF/applicationContext.xml”)。

所以,它ContextLoaderListener需要一个applicationContext.xml.

于 2013-03-18T14:13:49.393 回答
4

Spring 应用程序上下文是分层的。Web 应用程序中的典型安排是上下文加载器侦听器引导您的 AC 并使它们“全局”可用,然后每个单独的 DispatcherServlet 将具有自己的子应用程序上下文,可以“看到”所有 bean(通常是服务、数据源、等)来自上下文加载器侦听器的 AC。在所有情况下 - 当指定 ContextLoaderListener 或 DispatcherServlet - Spring 将自动(基于约定)查找 XML 应用程序上下文并尝试加载它。通常,您可以通过简单地指定一个空的 contextConfigLocation 参数 ("") 或告诉它它应该期望一个 Java 配置类来禁用它(contextClass 属性)。顺便说一句,可以有多个 DispatcherServlet。例如,您可能会 一个使用 Spring Integration 的入站 HTTP 适配器,另一个使用 Spring Web Services 端点,另一个使用 Spring MVC 应用程序,另一个使用 Spring HTTP 调用程序端点,它们都将通过 DispatcherServlet 公开。从理论上讲,您可以让它们都在同一个 DispatcherServlet 中工作,但隔离有助于保持事情不那么混乱,并且它们都可以共享相同的全局、更昂贵的 bean 的单个实例,例如 DataSources。

于 2013-03-19T18:07:34.200 回答
0

为确保您的应用不使用 applicationContext.xml,您可以执行类似的操作。您可以在这里看到这一切是如何结合在一起的。

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);
}
}
于 2016-12-01T01:42:27.003 回答