摘要: 在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

 




												

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

  1. Spring整合Hibernate的XML文件配置,以及web.xml文件配置

    利用Spring整合Hibernate时的XML文件配置 applicationContext.xml <?xml version="1.0" encoding=" ...

  2. java web工程web.xml介绍

    转载自:http://blog.csdn.net/believejava/article/details/43229361 Web.xml详解: 1.web.xml加载过程(步骤) 首先简单讲一下,w ...

  3. spring-第十七篇之spring AOP基于注解的零配置方式

    1.基于注解的零配置方式 Aspect允许使用注解定义切面.切入点和增强处理,spring框架可以识别并根据这些注解来生成AOP代理.spring只是用了和AspectJ 5一样的注解,但并没有使用A ...

  4. [spring]Bean注入——在XML中配置

    Bean注入的方式有两种: 一.在XML中配置 属性注入 构造函数注入 工厂方法注入 二.使用注解的方式注入@Autowired,@Resource,@Required 本文首先讲解在XML中配置的注 ...

  5. java web 3.1-web.xml文件配置

    <?xml version="1.0" encoding="UTF-8" ?> <web-app xmlns:xsi="http:/ ...

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

    为了在Spring中启动@AspectJ支持,需要在类加载路径下新增两个AspectJ库:aspectjweaver.jar和aspectjrt.jar.除此之外,Spring AOP还需要依赖一个a ...

  7. myeclipse中从svn下载的web工程,到工作空间却显示成Java工程

    转载自:https://blog.csdn.net/u011217058/article/details/57970587 右键工程,properties-> Project Facets-&g ...

  8. Spring JdbcTemplate + transactionTemplate 简单示例 (零配置)

    jdbcTemplate简介 Spring对数据库的操作在jdbc上面做了深层次的封装,使用spring的注入功能,可以把DataSource注册到JdbcTemplate之中. JdbcTempla ...

  9. 0077 web.xml中配置Spring MVC时,Servlet-name上报Servlet should have a mapping的错误

    这次是手工建立的web工程目录,在配置webapp/WEB-INF/web.xml的Spring MVC的DispatcherServlet时,在servlet-name上报错:Servlet sho ...

随机推荐

  1. Linux - 动态(Dynamic)与静态(Static)函数库

    首先我们要知道的是,函式库的类型有哪些?依据函式库被使用的类型而分为两大类,分别是静态 (Static) 与动态 (Dynamic) 函式库两类. 静态函式库的特色: 扩展名:(扩展名为 .a)   ...

  2. redis菜鸟教程

    Redis 简介 http://www.runoob.com/redis/redis-intro.html Redis 安装 http://www.runoob.com/redis/redis-ins ...

  3. 使用vs2010 opencv2.4.4编译release版本程序

    大体上要注意一下几点内容: 1.vc++目录的选择上,库目录选择为opencv目录中的staticlib目录 2.在链接->输入->附加依赖库,中添加,相应的staticlib库目录中的所 ...

  4. ruby利用Zip Gem写一个简单的压缩和解压的小工具

    在UNIX下的我们怎么会沦落到用ruby写压缩和解压工具呢?直接上shell啊!但是请允许本猫这次可耻的用ruby来玩玩吧!其实ruby GEM中有很多压缩解压包,我选的是Zip,也许是因为名字符合K ...

  5. 通向从容之道——Getting things done读书笔记

    一.主要的两个目的:         1. 抓住所有一切需要处理的事情:         2. 训练自己在接受一切"输入信息"的前期作出决定.   二.目前的问题:         ...

  6. 玩转Git入门篇

    最近项目使用到Git管理项目,所以就学习了一番,随然网上关于 Git的文章铺天盖地,我还是整理下总结下自己学习Git相关笔记,希望也能帮助到需要他的小伙伴们,O(∩_∩)O~ 简介 Git 是分布式版 ...

  7. C++内存分区

    C++的内存划分为栈区.堆区.全局区/静态区.字符串常量和代码区. 这里去掉自由存储区,增加了代码区,理由会在下面讲到. 栈区:由系统进行内存的管理. 说明:主要存放函数的参数以及局部变量.栈区由系统 ...

  8. Kotlin : Retrofit + RxAndroid + Realm

    https://jqs7.com/kotlin-retrofit-rxandroid-realm/ 原作者:Ahmed Rizwan 原文链接:Kotlin : Retrofit + RxAndroi ...

  9. (译) JSON-RPC 2.0 规范(中文版)

    http://wiki.geekdream.com/Specification/json-rpc_2.0.html 起源时间: 2010-03-26(基于2009-05-24版本) 更新: 2013- ...

  10. PHP中的 $_SERVER 函数说明详解

    用php在开发软件的时候,我们经常用到 $_SERVER[]这个函数,今天就来讲下这个数组的值,方便以后使用: A: $_SERVER['ARGC'] #包含传递给程序的 命令行参数的个数(如果运行在 ...