spring boot(1)--基础(servlet3+springMVC去除所有的xml)

在一些基于spring/spring mvc的java web项目中,总是会有一些xml配置文件,如web.xml、applicationContext.xml等,本文的目标是消除这些xml文件,使用代码和注解替代。由于本文是基于servlet3,所以首先采用的servlet3的容器,例如tomcat7以上版本、jetty8及以上版本。

消除web.xml

下面是一个典型的web.xml,包涵spring/spring mvc的配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?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容器启动的时候自动加载并运行。
将以上代码替换为Java代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class MyWebInitializer implements WebApplicationInitializer {
/**
* Servlet容器启动时会自动运行该方法
* @param servletContext
* @throws ServletException
*/
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
//初始化参数
servletContext.setInitParameter("contextConfigLocation","classpath:applicationContext" +
".xml");
//springMVC的servlet
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet());
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
dispatcher.setInitParameter("contextConfigLocation","classpath:dispatcher-servlet.xml");
//添加监听
servletContext.addListener(new ContextLoaderListener());
}
}

此时便可以删除web.xml。

去除spring mvc的配置文件dispatcher-servlet.xml

一个典型的spring mvc配置文件如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="org.wuqinghua.web"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>

Spring提供了@Configuration注解替代xml配置文件,@Bean注解可以替代xml中的来创建bean。将以上xml配置文件转换为Java代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
@Configuration
@EnableWebMvc //开启支持mvc
@ComponentScan(basePackages = "org.wuqinghua.web")
public class SpringMVCConfig {
@Bean
public InternalResourceViewResolver internalResourceViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}

去除spring配置文件applicationContext.xml

spring配置文件中的配置比较多,根据不同的项目还有不同的配置,一下提供了一个简单的配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="org.wuqinghua">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller"></context:exclude-filter>
</context:component-scan>
<context:property-placeholder location="classpath:dataSource.properties"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
</beans>

其中的配置文件dataSource.properties文件

1
2
3
4
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/taotao?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=root

将以上代码转换为java代码为

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
@Configuration
@ComponentScan(basePackages = "org.wuqinghua", excludeFilters = {@ComponentScan.Filter(value =
Controller.class)})
public class SpringConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
/**
* 必须添加static
*
* @return
*/
@Bean
public static PropertyPlaceholderConfigurer loadProperties() {
PropertyPlaceholderConfigurer placeholderConfigurer = new PropertyPlaceholderConfigurer();
ClassPathResource resource = new ClassPathResource("dataSource.properties");
placeholderConfigurer.setLocation(resource);
return placeholderConfigurer;
}
}

修改MyWebAppInitializer.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class MyWebInitializer implements WebApplicationInitializer {
/**
* Servlet容器启动时会自动运行该方法
*
* @param servletContext
* @throws ServletException
*/
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(SpringConfig.class);
servletContext.addListener(new ContextLoaderListener(rootContext));
AnnotationConfigWebApplicationContext webContext = new
AnnotationConfigWebApplicationContext();
webContext.register(SpringMVCConfig.class);
ServletRegistration.Dynamic registration = servletContext.addServlet("dispatcher", new DispatcherServlet(webContext));
registration.setLoadOnStartup(1);
registration.addMapping("/");
}
}