Spring全注解project示例 (无web.xml配置)

使用@Configuration注解配置类,实现spring MVC无web.xml配置.

 

1. project环境

    IDE: eclipse

    JDK: 1.7

    Server: tomcat7.0

 

2. 使用maven创建webapp, project Web Module 3.0

 

3. project的pom文件

 

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.homeway</groupId>
  <artifactId>testPrj</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>testPrj Maven Webapp</name>
  <url>http://maven.apache.org</url>
  
  <properties>
  	<spring.version>4.1.5.RELEASE</spring.version>
  </properties>  
  
  <dependencies>  
    <dependency>
    	<groupId>junit</groupId>
    	<artifactId>junit</artifactId>
    	<version>4.11</version>
    </dependency>
    <dependency>
    	<groupId>joda-time</groupId>
    	<artifactId>joda-time</artifactId>
    	<version>2.3</version>
    </dependency>
    <dependency>
    	<groupId>ch.qos.logback</groupId>
    	<artifactId>logback-classic</artifactId>
    	<version>1.1.1</version>
    </dependency>
    <dependency>
	    <groupId>com.google.guava</groupId>
	    <artifactId>guava</artifactId>
	    <version>18.0</version>
	</dependency>
    <dependency>
    	<groupId>org.apache.commons</groupId>
    	<artifactId>commons-lang3</artifactId>
    	<version>3.3.2</version>
    </dependency>
    <dependency>
    	<groupId>commons-beanutils</groupId>
    	<artifactId>commons-beanutils</artifactId>
    	<version>1.8.3</version>
    </dependency>
    <dependency>
    	<groupId>commons-io</groupId>
    	<artifactId>commons-io</artifactId>
    	<version>2.4</version>
    </dependency>
    <dependency>
    	<groupId>commons-fileupload</groupId>
    	<artifactId>commons-fileupload</artifactId>
    	<version>1.3.1</version>
    </dependency>
    <dependency>
    	<groupId>commons-collections</groupId>
    	<artifactId>commons-collections</artifactId>
    	<version>3.2.1</version>
    </dependency>
    <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-core</artifactId>
    	<version>${spring.version}</version>
    </dependency>
    <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-jdbc</artifactId>
    	<version>${spring.version}</version>
    </dependency>
    <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-webmvc</artifactId>
    	<version>${spring.version}</version>
    </dependency>
    <dependency>
	    <groupId>mysql</groupId>
	    <artifactId>mysql-connector-java</artifactId>
	    <version>5.1.34</version>
	</dependency>
    <dependency>
    	<groupId>javax.servlet</groupId>
    	<artifactId>jstl</artifactId>
    	<version>1.2</version>
    </dependency>
    <dependency>
    	<groupId>taglibs</groupId>
    	<artifactId>standard</artifactId>
    	<version>1.1.2</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>testPrj</finalName>
    <plugins>
    	<plugin>
    		<groupId>org.apache.maven.plugins</groupId>
    		<artifactId>maven-compiler-plugin</artifactId>
    		<version>3.1</version>
    		<configuration>
    			<source>1.7</source>
    			<target>1.7</target>
    		</configuration>
    	</plugin>
    </plugins>
  </build>
</project>

 

 

4. 编写类, 实现WebApplicationInitializer接口. 这个动作就相当于配置web.xml
    这个类的主要作用包含:
    (1) 获取spring的配置信息,等同于web.xml中为ContextLoaderListener配置spring的applicationContext.xml
    (2) 配置servlet和filter. 如配置spring的DispatcherServlet

 

package org.homeway.testPrj.springmvc;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class WebInit implements WebApplicationInitializer {
	
	Logger logger = LoggerFactory.getLogger(WebInit.class);

	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		/*
		 * ContextLoaderListener is added to ServletContext – 
		 * the purpose of this is to 'glue' WebApplicationContext 
		 * to the lifecycle of ServletContext		
		 */
		WebApplicationContext context = getContext();
		servletContext.addListener(new ContextLoaderListener(context));
		
		/*
		 * DispatcherServlet is created and initialized with 
		 * WebApplicationContext we have created, and it's 
		 * mapped to "/*" URLs and set to eagerly load on 
		 * application startup.
		 */
		ServletRegistration.Dynamic dispatcher = 
				servletContext.addServlet("DispatcherServlet", 
						new DispatcherServlet(context));
		dispatcher.setLoadOnStartup(1);
		dispatcher.addMapping("/");
				
	}
	
	private AnnotationConfigWebApplicationContext getContext() {
		 /*    
		 *     AnnotationConfigWebApplicationContext is created. 
		 *     It's WebApplicationContext implementation that 
		 * looks for Spring configuration in classes annotated
		 * with @Configuration annotation. 
		 *     setConfigLocation() method gets hint in which 
		 * package(s) to look for them.
		 */
		AnnotationConfigWebApplicationContext context = 
				new AnnotationConfigWebApplicationContext();
		context.scan("org.homeway.testPrj.springmvc.config");
		return context;
	}
}

 

 

5. 编写类, 配置spring
    这个类包含了:

    (1) bean的实例化与注入

    (2) ComponentScan的配置
    如何配置与读取porperties文件, 参考代码.

 

 

package org.homeway.testPrj.springmvc.config;

import javax.annotation.Resource;

import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

/*
 * The main AppConfig configuration class doesn't do anything 
 * but hits Spring on where to look for its components through
 * @ComponentScan annotation.
 */
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "org.homeway.testPrj")
@PropertySource("classpath:application.properties")
public class AppConfig {
	
	@Resource
	Environment env;
	
	@Bean(name="viewResolver")	
	public UrlBasedViewResolver setupViewResolver() {
		UrlBasedViewResolver viewResolver = new UrlBasedViewResolver();
		viewResolver.setPrefix("/WEB-INF/views/");
		viewResolver.setSuffix(".jsp");
		viewResolver.setViewClass(JstlView.class);
		viewResolver.setOrder(0);
		return viewResolver;
	}
	
	@Bean(name="dataSource")
	public BasicDataSource setupDataSource() {
		BasicDataSource dataSource = new BasicDataSource();
		dataSource.setDriverClassName(env.getProperty("db.driver"));
		dataSource.setUrl(env.getProperty("db.url"));
		dataSource.setUsername(env.getProperty("db.user"));
		dataSource.setPassword(env.getProperty("db.pwd"));
		return dataSource;
	}
	
	@Bean(name="jdbcTemplate")
	public JdbcTemplate setupJdbcTemplate(
			@Qualifier("dataSource")BasicDataSource dataSource) {
		return new JdbcTemplate(dataSource);
	}
	
	@Bean(name="dataSourceTransactionManager")
	public DataSourceTransactionManager setDataSourceTransactionManager(BasicDataSource dataSource){
		DataSourceTransactionManager tm = new DataSourceTransactionManager();
		tm.setDataSource(dataSource);
		return tm;
	}
}


6. 编写类, 继承WebMvcConfigurerAdapter类.

    这个类提供了许多void方法,复写这些方法以实现具体的配置

package org.homeway.testPrj.springmvc.config;

import java.util.List;

import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/*
 * WebMvcConfig class enables Spring MVC with @EnableWebMvc annotation.
 * It extends WebMvcConfigurerAdapter, which provides empty methods 
 * that can be overridden to customize default configuration of Spring
 * MVC. We will stick to default configuration at this time, but it’s
 * advised for you to see what the possibilities are.
 */
@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
	
	@Override	
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		//<mvc:resources mapping="/resources/**" location="/public-resources/"/>  
		registry.addResourceHandler("resources/**").addResourceLocations("/public-resources");
	}
	
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		// TODO Auto-generated method stub
		super.addInterceptors(registry);
	}
	
	@Override
	public void addArgumentResolvers(
			List<HandlerMethodArgumentResolver> argumentResolvers) {
		// TODO Auto-generated method stub
		super.addArgumentResolvers(argumentResolvers);
	}
	
	@Override
	public void addFormatters(FormatterRegistry registry) {
		// TODO Auto-generated method stub
		super.addFormatters(registry);
	}
	
	@Override
	public void addReturnValueHandlers(
			List<HandlerMethodReturnValueHandler> returnValueHandlers) {
		// TODO Auto-generated method stub
		super.addReturnValueHandlers(returnValueHandlers);
	}
	
	@Override
	public void addViewControllers(ViewControllerRegistry registry) {
		// TODO Auto-generated method stub
		super.addViewControllers(registry);
	}
	
	
	@Override
	public void configureMessageConverters(
			List<HttpMessageConverter<?>> converters) {
		// TODO Auto-generated method stub
		super.configureMessageConverters(converters);
	}
	
	@Override
	public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
		// TODO Auto-generated method stub
		super.extendMessageConverters(converters);
	}
	
	@Override
	public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
		// TODO Auto-generated method stub
		super.configureAsyncSupport(configurer);
	}
	
	@Override
	public void configureContentNegotiation(
			ContentNegotiationConfigurer configurer) {
		// TODO Auto-generated method stub
		super.configureContentNegotiation(configurer);
	}
	
	@Override
	public void configureDefaultServletHandling(
			DefaultServletHandlerConfigurer configurer) {
		// TODO Auto-generated method stub
		super.configureDefaultServletHandling(configurer);
	}
	
	@Override
	public void configureHandlerExceptionResolvers(
			List<HandlerExceptionResolver> exceptionResolvers) {
		// TODO Auto-generated method stub
		super.configureHandlerExceptionResolvers(exceptionResolvers);
	}
	
	@Override
	public void configurePathMatch(PathMatchConfigurer configurer) {
		// TODO Auto-generated method stub
		super.configurePathMatch(configurer);
	}
	
	@Override
	public void configureViewResolvers(ViewResolverRegistry registry) {
		// TODO Auto-generated method stub
		super.configureViewResolvers(registry);
	}
	
	
}

 

    7. 编写测试代码

   (略)

    

    8. 附件

 

 

 

你可能感兴趣的:(web.xml)