我是靠谱客的博主 等待曲奇,最近开发中收集的这篇文章主要介绍Servlet3 + SpringMVC零配置:去除所有的xml,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

转载来自:http://blog.csdn.net/xiao__gui/article/details/46803193

  • 编辑
  • 删除

在一些基于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的配置:

[html] view plain copy
print ?
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns="http://java.sun.com/xml/ns/javaee"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  
  5.     version="3.0">  
  6.   
  7.     <context-param>  
  8.         <param-name>contextConfigLocation</param-name>  
  9.         <param-value>classpath:applicationContext.xml</param-value>  
  10.     </context-param>  
  11.     <servlet>  
  12.         <servlet-name>dispatcher</servlet-name>  
  13.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  14.         <init-param>  
  15.             <param-name>contextConfigLocation</param-name>  
  16.             <param-value>classpath:dispatcher-servlet.xml</param-value>  
  17.         </init-param>  
  18.         <load-on-startup>1</load-on-startup>  
  19.     </servlet>  
  20.     <servlet-mapping>  
  21.         <servlet-name>dispatcher</servlet-name>  
  22.         <url-pattern>/</url-pattern>  
  23.     </servlet-mapping>  
  24.     <listener>  
  25.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  26.     </listener>  
  27.   
  28. </web-app>  
<?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代码:

[java] view plain copy
print ?
  1. public class MyWebAppInitializer implements WebApplicationInitializer {  
  2.   
  3.     /** 
  4.      * Servlet容器启动时会自动运行该方法 
  5.      */  
  6.     @Override  
  7.     public void onStartup(ServletContext servletContext) throws ServletException {  
  8.   
  9.         servletContext.setInitParameter("contextConfigLocation""classpath:applicationContext.xml");  
  10.   
  11.         ServletRegistration.Dynamic registration = servletContext.addServlet("dispatcher"new DispatcherServlet());  
  12.         registration.setLoadOnStartup(1);  
  13.         registration.addMapping("/");  
  14.         registration.setInitParameter("contextConfigLocation""classpath:dispatcher-servlet.xml");  
  15.   
  16.         servletContext.addListener(new ContextLoaderListener());  
  17.     }  
  18. }  
public class MyWebAppInitializer implements WebApplicationInitializer {

	/**
	 * Servlet容器启动时会自动运行该方法
	 */
	@Override
	public 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配置文件如下:

[html] view plain copy
print ?
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:context="http://www.springframework.org/schema/context"  
  4.     xmlns:mvc="http://www.springframework.org/schema/mvc"  
  5.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  6.     xsi:schemaLocation="  
  7.         http://www.springframework.org/schema/beans  
  8.         http://www.springframework.org/schema/beans/spring-beans.xsd  
  9.         http://www.springframework.org/schema/context  
  10.         http://www.springframework.org/schema/context/spring-context.xsd  
  11.         http://www.springframework.org/schema/mvc  
  12.         http://www.springframework.org/schema/mvc/spring-mvc.xsd">  
  13.    
  14.     <mvc:annotation-driven />  
  15.        
  16.     <context:component-scan base-package="com.xxg.controller" />  
  17.        
  18.     <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  19.         <property name="prefix" value="/WEB-INF/jsp/" />  
  20.         <property name="suffix" value=".jsp" />  
  21.     </bean>  
  22.        
  23. </beans>  
<?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/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
        http://www.springframework.org/schema/mvc
        http://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代码:

[java] view plain copy
print ?
  1. @Configuration  
  2. @EnableWebMvc  
  3. @ComponentScan(basePackages = "com.xxg.controller")  
  4. public class WebConfig {  
  5.       
  6.     @Bean  
  7.     public InternalResourceViewResolver internalResourceViewResolver() {  
  8.         InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();  
  9.         viewResolver.setPrefix("/WEB-INF/jsp/");  
  10.         viewResolver.setSuffix(".jsp");  
  11.         return viewResolver;  
  12.     }  
  13. }  
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.xxg.controller")
public class WebConfig {
	
	@Bean
	public InternalResourceViewResolver internalResourceViewResolver() {
		InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
		viewResolver.setPrefix("/WEB-INF/jsp/");
		viewResolver.setSuffix(".jsp");
		return viewResolver;
	}
}

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

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

[html] view plain copy
print ?
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:context="http://www.springframework.org/schema/context"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  6.         http://www.springframework.org/schema/beans/spring-beans.xsd  
  7.         http://www.springframework.org/schema/context  
  8.         http://www.springframework.org/schema/context/spring-context.xsd">  
  9.   
  10.     <context:component-scan base-package="com.xxg">  
  11.         <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />  
  12.     </context:component-scan>  
  13.       
  14.     <context:property-placeholder location="classpath:config.properties"/>  
  15.       
  16.     <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">  
  17.         <property name="driverClassName" value="${jdbc.driverClassName}"/>  
  18.         <property name="url" value="${jdbc.url}"/>  
  19.         <property name="username" value="${jdbc.username}"/>  
  20.         <property name="password" value="${jdbc.password}"/>  
  21.     </bean>  
  22.   
  23. </beans>  
<?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/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="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配置文件读取:

[plain] view plain copy
print ?
  1. jdbc.driverClassName=com.mysql.jdbc.Driver  
  2. jdbc.url=jdbc:mysql://localhost:3306/mydb  
  3. jdbc.username=root  
  4. jdbc.password=123456  
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mydb
jdbc.username=root
jdbc.password=123456

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

[java] view plain copy
print ?
  1. @Configuration  
  2. @ComponentScan(basePackages = "com.xxg", excludeFilters = {@Filter(value = Controller.class)})  
  3. public class AppConfig {  
  4.        
  5.     @Value("${jdbc.driverClassName}")  
  6.     private String driverClassName;  
  7.        
  8.     @Value("${jdbc.url}")  
  9.     private String url;  
  10.    
  11.     @Value("${jdbc.username}")  
  12.     private String username;  
  13.    
  14.     @Value("${jdbc.password}")  
  15.     private String password;  
  16.    
  17.     @Bean(destroyMethod = "close")  
  18.     public DataSource dataSource() {  
  19.         BasicDataSource dataSource = new BasicDataSource();  
  20.         dataSource.setDriverClassName(driverClassName);  
  21.         dataSource.setUrl(url);  
  22.         dataSource.setUsername(username);  
  23.         dataSource.setPassword(password);  
  24.         return dataSource;  
  25.     }  
  26.       
  27.     /** 
  28.      * 必须加上static 
  29.      */  
  30.     @Bean  
  31.     public static PropertyPlaceholderConfigurer loadProperties() {  
  32.         PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();  
  33.         ClassPathResource resource = new ClassPathResource("config.properties");  
  34.         configurer.setLocations(resource);  
  35.         return configurer;  
  36.     }  
  37. }  
@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
     */
    @Bean
    public static PropertyPlaceholderConfigurer loadProperties() {
        PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
        ClassPathResource resource = new ClassPathResource("config.properties");
        configurer.setLocations(resource);
        return configurer;
    }
}

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

[java] view plain copy
print ?
  1. @Configuration  
  2. @ComponentScan(basePackages = "com.xxg", excludeFilters = {@Filter(value = Controller.class)})  
  3. @PropertySource("classpath:config.properties")  
  4. public class AppConfig {  
  5.       
  6.     @Value("${jdbc.driverClassName}")  
  7.     private String driverClassName;  
  8.       
  9.     @Value("${jdbc.url}")  
  10.     private String url;  
  11.   
  12.     @Value("${jdbc.username}")  
  13.     private String username;  
  14.   
  15.     @Value("${jdbc.password}")  
  16.     private String password;  
  17.   
  18.     @Bean(destroyMethod = "close")  
  19.     public DataSource dataSource() {  
  20.         BasicDataSource dataSource = new BasicDataSource();  
  21.         dataSource.setDriverClassName(driverClassName);  
  22.         dataSource.setUrl(url);  
  23.         dataSource.setUsername(username);  
  24.         dataSource.setPassword(password);  
  25.         return dataSource;  
  26.     }  
  27.       
  28.     /** 
  29.      * 必须加上static 
  30.      */  
  31.     @Bean  
  32.     public static PropertySourcesPlaceholderConfigurer loadProperties() {  
  33.         PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();  
  34.         return configurer;  
  35.     }  
  36. }  
@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
     */
    @Bean
    public 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:

[java] view plain copy
print ?
  1. public class MyWebAppInitializer implements WebApplicationInitializer {  
  2.   
  3.     /** 
  4.      * Servlet容器启动时会自动运行该方法 
  5.      */  
  6.     @Override  
  7.     public void onStartup(ServletContext servletContext) throws ServletException {  
  8.            
  9.         AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();  
  10.         rootContext.register(AppConfig.class);  
  11.         servletContext.addListener(new ContextLoaderListener(rootContext));  
  12.            
  13.         AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext();  
  14.         webContext.register(WebConfig.class);  
  15.         ServletRegistration.Dynamic registration = servletContext.addServlet("dispatcher"new DispatcherServlet(webContext));  
  16.         registration.setLoadOnStartup(1);  
  17.         registration.addMapping("/");  
  18.     }  
  19. }  
public class MyWebAppInitializer implements WebApplicationInitializer {

    /**
     * Servlet容器启动时会自动运行该方法
     */
    @Override
    public 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配置文件。


参考:
http://blog.csdn.net/u012578322/article/details/61936505
http://blog.csdn.net/w_x_z_/article/details/53336530
在这里对我的疑问“项目启动时,web容器怎样加载Initializer”作了回答:
以往都是通过web.xml文件来关联spring配置的,那这里的web.xml文件里面没有配置,是怎样拉起spring的呢?原因就在于Initializer类继承了AbstractAnnotationConfigDispatcherServletInitializer。此时,Initializer的作用域就类似以前的spring-context.xml,并且会在web项目运行初始化被自动发现并加载,这就是java config的魅力所在了,不管在哪里声明了配置,只要继承了AbstractAnnotationConfigDispatcherServletInitializer,它就可以被自动加载。


最后

以上就是等待曲奇为你收集整理的Servlet3 + SpringMVC零配置:去除所有的xml的全部内容,希望文章能够帮你解决Servlet3 + SpringMVC零配置:去除所有的xml所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(44)

评论列表共有 0 条评论

立即
投稿
返回
顶部