在一些基于Spring/Spring MVC的Java Web项目中,总是会有一些xml配置文件,如web.xml、applicationContext.xml等,本文的目标即消灭这些xml配置文件,用代码和注解来代替。

由于本文是基于Servlet 3,所以首先需要准备支持Servlet 3的容器,例如Tomcat 7.0及以上版本、Jetty 8及以上版本。

1、去除web.xml

下面是一个典型的web.xml,包含Spring/Spring MVC的配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"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>contextConfigLocation</param-name><param-value>classpath:applicationContext.xml</param-value></context-param><servlet><servlet-name>dispatcher</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:dispatcher-servlet.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>dispatcher</servlet-name><url-pattern>/</url-pattern></servlet-mapping><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener></web-app>

下一步是去除web.xml文件,用Java代码代替它。

Spring MVC提供了一个接口WebApplicationInitializer,用于替代web.xml配置文件。实现该接口的类会在Servlet容器启动时自动加载并运行。

将以上xml文件转换成Java代码:

public class MyWebAppInitializer implements WebApplicationInitializer {/*** Servlet容器启动时会自动运行该方法*/@Overridepublic void onStartup(ServletContext servletContext) throws ServletException {servletContext.setInitParameter("contextConfigLocation", "classpath:applicationContext.xml");ServletRegistration.Dynamic registration = servletContext.addServlet("dispatcher", new DispatcherServlet());registration.setLoadOnStartup(1);registration.addMapping("/");registration.setInitParameter("contextConfigLocation", "classpath:dispatcher-servlet.xml");servletContext.addListener(new ContextLoaderListener());}
}

此时便可删除web.xml。

2、去除Spring MVC配置文件dispatcher-servlet.xml

一个典型的Spring MVC配置文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd"><mvc:annotation-driven /><context:component-scan base-package="com.xxg.controller" /><bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/jsp/" /><property name="suffix" value=".jsp" /></bean></beans>

Spring提供了@Configuration注解用于替代xml配置文件,@Bean注解可以替代xml中的<bean>来创建bean。

将以上xml配置文件转换成Java代码:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.xxg.controller")
public class WebConfig {@Beanpublic InternalResourceViewResolver internalResourceViewResolver() {InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();viewResolver.setPrefix("/WEB-INF/jsp/");viewResolver.setSuffix(".jsp");return viewResolver;}
}

3、去除Spring配置文件applicationContext.xml

Spring的配置文件中内容可能会比较多,并且不同的项目会有不同的配置,以下提供了一个简单的配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"><context:component-scan base-package="com.xxg"><context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /></context:component-scan><context:property-placeholder location="classpath:config.properties"/><bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"><property name="driverClassName" value="${jdbc.driverClassName}"/><property name="url" value="${jdbc.url}"/><property name="username" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/></bean></beans>

其中数据库的相关配置从config.properties配置文件读取:

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mydb
jdbc.username=root
jdbc.password=123456

将以上xml配置转换成Java代码:

@Configuration
@ComponentScan(basePackages = "com.xxg", excludeFilters = {@Filter(value = Controller.class)})
public class AppConfig {@Value("${jdbc.driverClassName}")private String driverClassName;@Value("${jdbc.url}")private String url;@Value("${jdbc.username}")private String username;@Value("${jdbc.password}")private String password;@Bean(destroyMethod = "close")public DataSource dataSource() {BasicDataSource dataSource = new BasicDataSource();dataSource.setDriverClassName(driverClassName);dataSource.setUrl(url);dataSource.setUsername(username);dataSource.setPassword(password);return dataSource;}/*** 必须加上static*/@Beanpublic static PropertyPlaceholderConfigurer loadProperties() {PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();ClassPathResource resource = new ClassPathResource("config.properties");configurer.setLocations(resource);return configurer;}
}

除了上面的方法外,加载properties配置文件还可以使用@PropertySource注解,Java代码也可以这样写:

@Configuration
@ComponentScan(basePackages = "com.xxg", excludeFilters = {@Filter(value = Controller.class)})
@PropertySource("classpath:config.properties")
public class AppConfig {@Value("${jdbc.driverClassName}")private String driverClassName;@Value("${jdbc.url}")private String url;@Value("${jdbc.username}")private String username;@Value("${jdbc.password}")private String password;@Bean(destroyMethod = "close")public DataSource dataSource() {BasicDataSource dataSource = new BasicDataSource();dataSource.setDriverClassName(driverClassName);dataSource.setUrl(url);dataSource.setUsername(username);dataSource.setPassword(password);return dataSource;}/*** 必须加上static*/@Beanpublic static PropertySourcesPlaceholderConfigurer loadProperties() {PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();return configurer;}
}

以上两种Java编码方式选择其中一种即可。

4、修改MyWebAppInitializer.java

完成以上步骤后,就可以去掉dispatcher-servlet.xml和applicationContext.xml等Spring配置文件,用Java代码替代了。

此时,第1步中的MyWebAppInitializer.java需要修改,不再读取xml配置文件,而是加载@Configuration注解的Java代码来配置Spring:

public class MyWebAppInitializer implements WebApplicationInitializer {/*** Servlet容器启动时会自动运行该方法*/@Overridepublic void onStartup(ServletContext servletContext) throws ServletException {AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();rootContext.register(AppConfig.class);servletContext.addListener(new ContextLoaderListener(rootContext));AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext();webContext.register(WebConfig.class);ServletRegistration.Dynamic registration = servletContext.addServlet("dispatcher", new DispatcherServlet(webContext));registration.setLoadOnStartup(1);registration.addMapping("/");}
}

至此,便完成了Java程序替换xml配置文件。

Servlet 3 + Spring MVC零配置:去除所有xml相关推荐

  1. Spring MVC零配置(全注解)(版本5.0.7)

    // 核心配置类 package spittr.config;import org.springframework.web.servlet.support.AbstractAnnotationConf ...

  2. spring boot 源码解析15-spring mvc零配置

    前言 spring boot 是基于spring 4 的基础上的一个框架,spring 4 有一个新特效–>基于java config 实现零配置.而在企业的实际工作中,spring 都是和sp ...

  3. Spring MVC 事务配置

    Spring MVC事务配置 要了解事务配置的所有方法,请看一下<Spring事务配置的5种方法> 本文介绍两种配置方法: 一.      XML,使用tx标签配置拦截器实现事务 一.   ...

  4. spring mvc mysql配置_spring mvc配置数据库连接

    ACM 配置中心实战:Spring + MyBatis + Druid + ACM 很多基于 Spring MVC 框架的 Web 开发中,Spring + MyBatis + Druid 是一个黄金 ...

  5. Spring boot的Spring MVC自动配置原理

    Spring MVC自动配置 搜索WebMvcAutoConfiguration 查询ContentNegotiatingViewResolver ContentNegotiatingViewReso ...

  6. JSP、Servlet和Spring MVC

    今年刚接触JavaWeb的时候碰巧认识了一帮老师做后端的哥们,我俩平时用的最多的也都是Java. 我:"老哥,我想给我那个项目做一个服务器应用程序,怎么搞啊" 老哥:"S ...

  7. Spring MVC的WebMvcConfigurerAdapter用法收集(零配置,无XML配置)

    原理先不了解,只记录常用方法 用法: @EnableWebMvc 开启MVC配置,相当于 <?xml version="1.0" encoding="UTF-8&q ...

  8. web框架的前生今世--从servlet到spring mvc到spring boot

    背景 上世纪90年代,随着Internet和浏览器的飞速发展,基于浏览器的B/S模式随之火爆发展起来.最初,用户使用浏览器向WEB服务器发送的请求都是请求静态的资源,比如html.css等.  但是可 ...

  9. spring mvc 入门配置

    1. 把所需jar拷贝到工程目录下WEB-INF/lib 2. 配置WEB.xml,配置前端控制器 org.springframework.web.servlet.DispatcherServlet ...

最新文章

  1. 2021中青杯数学建模C题 在线教学的分析与研究
  2. 20-100-040-安装-Centos 7.5 安装MYSQL
  3. 用Python编写干净 可测试 高质量的代码
  4. 关于 ssh-keygen 的一点疑问
  5. tensorflow之卷积神经网络
  6. java 置位_java安全编码指南之:Mutability可变性详解
  7. Python 首超 Java 雄霸5月编程语言指数榜!
  8. 拓端tecdat|基于r语言的疾病制图中自适应核密度估计的阈值选择方法案例
  9. 奇门遁甲排盘软件 Alpha 0.4 发布
  10. Win10专业工作站版的Ghost备份与还原
  11. 计算机考试用户注册,全国计算机等级考试(NCRE)
  12. cookie.setValue一些注意事项
  13. 多媒体计算机技术中处理的媒体元素,系统架构设计师多媒体技术基本概念
  14. 华为hana服务器型号齐全,华为宣布工业服务器通过SAP HANA认证
  15. 自整理---Mysql高级笔记
  16. 史上最全vue优化方案
  17. 对struct cred新理解
  18. leetcode 大礼包
  19. 男子在网吧蜗居4年半 曾647分考上大学 IS2120@BG57IV3
  20. 红旗颂的感情多么真挚,突然很理解老一代们:-)

热门文章

  1. Vue 3 父子组件传递数据的几种通信方式 (Prop、自定义事件、v-model...)
  2. 腾讯科恩实验室吴石,站在 0 和 1 之间的人
  3. matlab 矩阵数组知识
  4. Unity骰子插值旋转的投掷功能,获得正面点数(可按钮控制上下左右插值翻转,无万向锁问题)
  5. 从2.0到3.0,安全可信正在成为云原生的下一核心
  6. EMQX 安装使用和部分坑
  7. 如何批量给文件夹名加上相同的前缀?
  8. 返回键点击触发,回到桌面
  9. VIVADO仿真功能系列
  10. rto净化效率计算公式_管理效率计算公式