Spring Web工程web.xml零配置即使用Java Config + Annotation

摘要: 在Spring 3.0之前,我们工程中常用Bean都是通过XML形式的文件注解的,少了还可以,但是数量多,关系复杂到后期就很难维护了,所以在3.x之后Spring官方推荐使用Java Config方式去替换以前冗余的XML格式文件的配置方式;

在开始之前,我们需要注意一下,要基于Java Config实现无web.xml的配置,我们的工程的Servlet必须是3.0及其以上的版本;

1、我们要实现无web.xml的配置,只需要关注实现WebApplicationInitializer这个接口,以下为Spring源码:

public interface WebApplicationInitializer {

    /**
     * Configure the given {@link ServletContext} with any servlets, filters, listeners
     * context-params and attributes necessary for initializing this web application. See
     * examples {@linkplain WebApplicationInitializer above}.
     * @param servletContext the {@code ServletContext} to initialize
     * @throws ServletException if any call against the given {@code ServletContext}
     * throws a {@code ServletException}
     */
    void onStartup(ServletContext servletContext) throws ServletException;

}

2、我们这里先不讲他的原理,只要我们工程中实现这个接口的类,Spring容器在启动时候就会监听到我们所实现的这个类,从而读取我们的配置,就如读取web.xml一样,我们的实现类如下所示:

public class WebProjectConfigInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container) {

        initializeSpringConfig(container);

        initializeLog4jConfig(container);

        initializeSpringMVCConfig(container);

        registerServlet(container);

        registerListener(container);

        registerFilter(container);
    }

    private void initializeSpringConfig(ServletContext container) {
        // Create the ‘root‘ Spring application context
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(AppConfiguration.class);
        // Manage the life cycle of the root application context
        container.addListener(new ContextLoaderListener(rootContext));
    }

    private void initializeSpringMVCConfig(ServletContext container) {
        // Create the spring rest servlet‘s Spring application context
        AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
        dispatcherContext.register(RestServiceConfiguration.class);

        // Register and map the spring rest servlet
        ServletRegistration.Dynamic dispatcher = container.addServlet("SpringMvc",
                new DispatcherServlet(dispatcherContext));
        dispatcher.setLoadOnStartup(2);
        dispatcher.setAsyncSupported(true);
        dispatcher.addMapping("/springmvc/*");
    }

    private void initializeLog4jConfig(ServletContext container) {
        // Log4jConfigListener
        container.setInitParameter("log4jConfigLocation", "file:${rdm.home}/log4j.properties");
        container.addListener(Log4jConfigListener.class);
        PropertyConfigurator.configureAndWatch(System.getProperty("rdm.home") + "/log4j.properties", 60);
    }

    private void registerServlet(ServletContext container) {

        initializeStaggingServlet(container);
    }

    private void registerFilter(ServletContext container) {
        initializeSAMLFilter(container);
    }

    private void registerListener(ServletContext container) {
        container.addListener(RequestContextListener.class);
    }

    private void initializeSAMLFilter(ServletContext container) {
        FilterRegistration.Dynamic filterRegistration = container.addFilter("SAMLFilter", DelegatingFilterProxy.class);
        filterRegistration.addMappingForUrlPatterns(null, false, "/*");
        filterRegistration.setAsyncSupported(true);
    }

    private void initializeStaggingServlet(ServletContext container) {
        StaggingServlet staggingServlet = new StaggingServlet();
        ServletRegistration.Dynamic dynamic = container.addServlet("staggingServlet", staggingServlet);
        dynamic.setLoadOnStartup(3);
        dynamic.addMapping("*.stagging");
    }
}

3、以上的Java Config等同于如下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_3_0.xsd"
    version="3.0">
    <context-param>
        <param-name>contextClass</param-name>
        <param-value>
            org.springframework.web.context.support.AnnotationConfigWebApplicationContext
        </param-value>
    </context-param>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>com.g360.configuration.AppConfiguration</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
     <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>file:${rdm.home}/log4j.properties</param-value>
    </context-param>
     <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener> 

    <servlet>
        <description>staggingServlet</description>
        <display-name>staggingServlet</display-name>
        <servlet-name>staggingServlet</servlet-name>
        <servlet-class>com.g360.bean.interfaces.StaggingServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>staggingServlet</servlet-name>
        <url-pattern>*.stagging</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>SpringMvc</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>com.g360.configuration.RestServiceConfiguration</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringMvc</servlet-name>
        <url-pattern>/springmvc/*</url-pattern>
    </servlet-mapping>
    <filter>
        <filter-name>SAMLFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        <async-supported>true</async-supported>
     </filter>
    <filter-mapping>
    <filter-name>SAMLFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>

    <welcome-file-list>
        <welcome-file>login.jsp</welcome-file>
    </welcome-file-list>
</web-app>

4、我们分类解读,在web.xml配置里面我们配置的Web Application Context

    <context-param>
        <param-name>contextClass</param-name>
        <param-value>
            org.springframework.web.context.support.AnnotationConfigWebApplicationContext
        </param-value>
    </context-param>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>com.g360.configuration.AppConfiguration</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

就等价于Java Config中的

private void initializeSpringConfig(ServletContext container) {
        // Create the ‘root‘ Spring application context
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(AppConfiguration.class);
        // Manage the life cycle of the root application context
        container.addListener(new ContextLoaderListener(rootContext));
}

如此推断,在web.xml配置里面我们配置的log4j

<context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>file:${rdm.home}/log4j.properties</param-value>
</context-param>
<listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener> 

就等价于Java Config的

    private void initializeLog4jConfig(ServletContext container) {
        // Log4jConfigListener
        container.setInitParameter("log4jConfigLocation", "file:${rdm.home}/log4j.properties");
        container.addListener(Log4jConfigListener.class);
        PropertyConfigurator.configureAndWatch(System.getProperty("rdm.home") + "/log4j.properties", 60);
    }

类此,在web.xml配置里面我们配置的Spring Web(Spring Restful)

    <servlet>
        <servlet-name>SpringMvc</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>com.g360.configuration.RestServiceConfiguration</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringMvc</servlet-name>
        <url-pattern>/springmvc/*</url-pattern>
    </servlet-mapping>

就等价于Java Config中的

private void initializeSpringMVCConfig(ServletContext container) {
        // Create the spring rest servlet‘s Spring application context
        AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
        dispatcherContext.register(RestServiceConfiguration.class);

        // Register and map the spring rest servlet
        ServletRegistration.Dynamic dispatcher = container.addServlet("SpringMvc",
                new DispatcherServlet(dispatcherContext));
        dispatcher.setLoadOnStartup(2);
        dispatcher.setAsyncSupported(true);
        dispatcher.addMapping("/springmvc/*");
}

再此,在web.xml配置里面我们配置的servlet

    <servlet>
        <description>staggingServlet</description>
        <display-name>staggingServlet</display-name>
        <servlet-name>staggingServlet</servlet-name>
        <servlet-class>com.g360.bean.interfaces.StaggingServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>staggingServlet</servlet-name>
        <url-pattern>*.stagging</url-pattern>
    </servlet-mapping>

就等价于Java Config中的

    private void initializeStaggingServlet(ServletContext container) {
        StaggingServlet staggingServlet = new StaggingServlet();
        ServletRegistration.Dynamic dynamic = container.addServlet("staggingServlet", staggingServlet);
        dynamic.setLoadOnStartup(3);
        dynamic.addMapping("*.stagging");
    }

后面以此类推,在这里不加详述了;

5、如上面所说的,我们对Web 工程的整体配置都依赖于AppConfiguration这个配置类,下面是使用@Configuration 配置类注解的,大家使用过的,以此类推,都比较清楚,

这里就不加赘述了;

@Configuration
@EnableTransactionManagement
@EnableAsync
@EnableAspectJAutoProxy
@EnableScheduling
@Import({ RestServiceConfiguration.class, BatchConfiguration.class, DatabaseConfiguration.class, ScheduleConfiguration.class})
@ComponentScan({ "com.service", "com.dao", "com.other"})
public class AppConfiguration
{

  private Logger logger = LoggerFactory.getLogger(AppConfiguration.class);

  /**
   *
   */
  public AppConfiguration ()
  {
    // TODO Auto-generated constructor stub
    logger.info("[Initialize application]");
    Locale.setDefault(Locale.US);
  }

}

还有就是对Spring Web配置的类RestServiceConfiguration ,个人可根据自己的实际项目需求在此配置自己的视图类型以及类型转换等等

@Configuration
@EnableWebMvc
@EnableAspectJAutoProxy(proxyTargetClass = true)
@ComponentScan(basePackages = { "com.bean" })
public class RestServiceConfiguration extends WebMvcConfigurationSupport {

    @Bean
    public RequestMappingHandlerAdapter requestMappingHandlerAdapter() {
        RequestMappingHandlerAdapter handlerAdapter = super.requestMappingHandlerAdapter();
        return handlerAdapter;
    }

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        return new LocaleChangeInterceptor();
    }

    @Bean
    public LogAspect logAspect() {
        return new LogAspect();
    }
}

至此,我们的 web.xml使用Java Config零配置就完了

https://my.oschina.net/521cy/blog/702864





				
时间: 2024-10-24 12:03:22

Spring Web工程web.xml零配置即使用Java Config + Annotation的相关文章

Spring AOP基于注解的“零配置”方式

Spring AOP基于注解的“零配置”方式: Spring的beans.xml中 <!-- 指定自动搜索Bean组件.自动搜索切面类 --> <context:component-scan base-package="org.crazyit.app.service,org.crazyit.app.aspect"> <context:include-filter type="annotation" expression="or

Spring事务管理--[基于XML的配置]

我觉得自己写的不好,所以先贴一个写的好的帖子 感觉看完不用回来了.... 这是一个大佬写的的博客 : https://www.cnblogs.com/yixianyixian/p/8372832.html 第一:JavaEE 体系进行分层开发,事务处理位于业务层,Spring 提供了分层设计业务层的事务处理解决方 案. 第二:spring 框架为我们提供了一组事务控制的接口.具体在后面的第二小节介绍.这组接口是在 spring-tx-5.0.2.RELEASE.jar 中. 第三:spring

Spring AOP基于注解的“零配置”方式---org.springframework.beans.factory.BeanNotOfRequiredTypeException

具体异常信息如下: 1 Exception in thread "main" org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'hello' must be of type [com.hyq.chapter08_04_3.HelloImpl], but was actually of type [com.sun.proxy.$Proxy13] 2 at org.springfram

Idea利用SpringMVC创建servlet web工程需要的maven配置

1.如果不需要spring mvc,删除相关dependency即可. 2.Idea->pom.xml <!-- 以下为创建java spring mvc restful风格使用的jar包 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</ver

Spring AOP基于注解的“零配置”方式实现

为了在Spring中启动@AspectJ支持,需要在类加载路径下新增两个AspectJ库:aspectjweaver.jar和aspectjrt.jar.除此之外,Spring AOP还需要依赖一个aopalliance.jar包 定义一个类似ServiceAspect.java这样的切面bean: 1 package com.hyq.aop; 2 3 import org.apache.commons.logging.Log; 4 import org.apache.commons.loggi

Spring系列【7】零配置实现Bean的注入

与前几例不同,需要导入aop包. Book.java 注意Book类@Component 1 package cn.com.xf; 2 3 import org.springframework.stereotype.Component; 4 5 @Component 6 public class Book { 7 private String name="JAVA从入门到精通"; 8 private double price=45.67; 9 public String getName

Maven快速创建SpringMVC web工程详解(2)

一.前言 在上一篇文章中,讲解了如何用maven创建web工程,并简单搭建基于Spring框架的MVC工程,但是配置较为简单,很多配置尚未涉及:本文对 Spring MVC工程的更多详细配置.使用,进行进一步的讲解,搭建一个完整.可用的Spring web工程框架. 二.配置文件目录放置修改 根据maven工程提倡的标准目录结构,我们将/WEB-INF/目录下的Spring配置文件移到 /src/main/resources/ 目录下:而因为Spring默认加载的配置文件目录为/WEB-INF/

Spring4.X + spring MVC + Mybatis3 零配置应用开发框架搭建详解(1) - 基本介绍

Spring4.X + spring MVC + Mybatis3 零配置应用开发框架搭建详解(1) - 基本介绍 spring集成 mybatis Spring4.x零配置框架搭建 两年前一直在做后台的纯Java开发,很少涉及web开发这块,最近换了个纯的互联网公司,需要做Web后台管理系统,之前都是用xml配置的项目,接触了公司Spring4.x的零配置项目,觉得非常有感觉,不仅仅配置简单,而且条理清晰,所以,这里把学习的内容记录下来,一来加深对这块技术的印象,另外准备做个简单的教程,如果给

eclipse+maven+tomcat构建web工程

我们要利用Maven构建一个web应用,开发环境为eclipse+tomcat.构建过程如下: 1.工具准备 eclipse:版本为eclipse 4.2(Juno Service),maven插件的安装与配置参见"m2eclipse安装与配置" tomcat:版本为apache-tomcat-6.0.37(即tomcat6.x系列,本文安装在D:\work\tomcat6\apache-tomcat-6.0.37-maven) 2.建立web应用 我们使用eclipse建立maven