Spring MVC 完全注解方式配置web项目
在 servlet 3.0 开始web项目可以完全不需要web.xml配置文件了,所以本文的配置只在支持servlet 3.0及以上的web容器中有效
使用的是spring mvc (4.3.2.RELEASE) + thymeleaf(3.0.2.RELEASE), 持久层使用的 spring的 JdbcTemplate, PS:推荐一个很好用的对JdbcTemplate封装的框架:https://github.com/selfly/dexcoder-assistant 。 下面开始具体的配置:
配置spring mvc DispatcherServlet
DispatcherServlet 是spring mvc的核心, Spring 提供了一个快速配置DispatcherServlet的类 AbstractAnnotationConfigDispatcherServletInitializer,具体代码如下:
其中 onStartup() 是 WebApplicationInitializer 接口中的方法,用户配置其他的 filter 和 listener
getRootConfigClasses() 获取配置类,我理解的相当于 applicationContext.xml 创建的上下文
getServletConfigClasses()获取配置类,相当于 mvc-servlet.xml 创建的上下文
此类上不需要任何注解,
1 package com.liulu.bank.config; 2 3 import org.springframework.web.WebApplicationInitializer; 4 import org.springframework.web.filter.CharacterEncodingFilter; 5 import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; 6 7 import javax.servlet.FilterRegistration; 8 import javax.servlet.ServletContext; 9 import javax.servlet.ServletException; 10 import java.nio.charset.StandardCharsets; 11 12 /** 13 * User : liulu 14 * Date : 2016-10-7 15:12 15 */ 16 public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer implements WebApplicationInitializer { 17 18 @Override 19 protected Class<?>[] getRootConfigClasses() { 20 return new Class<?>[]{RootConfig.class}; 21 } 22 23 @Override 24 protected Class<?>[] getServletConfigClasses() { 25 return new Class<?>[]{WebConfig.class}; 26 } 27 28 /** 29 * 配置DispatcherServlet 匹配的路径 30 * @return 31 */ 32 @Override 33 protected String[] getServletMappings() { 34 return new String[]{"/"}; 35 } 36 37 /** 38 * 配置其他的 servlet 和 filter 39 * 40 * @param servletContext 41 * @throws ServletException 42 */ 43 @Override 44 public void onStartup(ServletContext servletContext) throws ServletException { 45 FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("encodingFilter", CharacterEncodingFilter.class); 46 encodingFilter.setInitParameter("encoding", String.valueOf(StandardCharsets.UTF_8)); 47 encodingFilter.setInitParameter("forceEncoding", "true"); 48 encodingFilter.addMappingForUrlPatterns(null, false, "/*"); 49 } 50 }
配置 applicationContext.xml,由RootConfig类实现
1 package com.liulu.bank.config; 2 3 import com.mchange.v2.c3p0.ComboPooledDataSource; 4 import org.springframework.context.annotation.*; 5 import org.springframework.core.env.Environment; 6 import org.springframework.jdbc.core.JdbcTemplate; 7 import org.springframework.jdbc.datasource.DataSourceTransactionManager; 8 import org.springframework.stereotype.Controller; 9 import org.springframework.transaction.PlatformTransactionManager; 10 import org.springframework.transaction.annotation.EnableTransactionManagement; 11 12 import javax.annotation.Resource; 13 import javax.sql.DataSource; 14 import java.beans.PropertyVetoException; 15 16 /** 17 * User : liulu 18 * Date : 2016-10-7 15:36 19 */ 20 @Configuration 21 @PropertySource("classpath:config.properties") // 导入属性文件 22 @EnableAspectJAutoProxy // 相当于 xml 中的 <aop:aspectj-autoproxy/> 23 @EnableTransactionManagement // 开启注解事务 24 @ComponentScan(basePackages = {"com.liulu.lit", "com.liulu.bank"}, excludeFilters = @ComponentScan.Filter(classes = Controller.class )) 25 public class RootConfig { 26 27 // 上面导入的属性文件中的属性会 注入到 Environment 中 28 @Resource 29 private Environment env; 30 31 /** 32 * 配置数据库连接池 c3p0, 33 * @return 34 * @throws PropertyVetoException 35 */ 36 @Bean 37 public DataSource dataSource() throws PropertyVetoException { 38 ComboPooledDataSource dataSource = new ComboPooledDataSource(); 39 dataSource.setJdbcUrl(env.getProperty("db.url")); 40 dataSource.setDriverClass(env.getProperty("db.driver")); 41 dataSource.setUser(env.getProperty("db.user")); 42 dataSource.setPassword(env.getProperty("db.password")); 43 dataSource.setMinPoolSize(Integer.valueOf(env.getProperty("pool.minPoolSize"))); 44 dataSource.setMaxPoolSize(Integer.valueOf(env.getProperty("pool.maxPoolSize"))); 45 dataSource.setAutoCommitOnClose(false); 46 dataSource.setCheckoutTimeout(Integer.valueOf(env.getProperty("pool.checkoutTimeout"))); 47 dataSource.setAcquireRetryAttempts(2); 48 return dataSource; 49 } 50 51 /** 52 * 配置事物管理器 53 * @param dataSource 54 * @return 55 */ 56 @Bean 57 public PlatformTransactionManager transactionManager(DataSource dataSource) { 58 return new DataSourceTransactionManager(dataSource); 59 } 60 61 @Bean 62 public JdbcTemplate jdbcTemplate (DataSource dataSource) { 63 return new JdbcTemplate(dataSource); 64 } 65 66 67 }
config.properties 文件在 resources 目录下
#数据库配置 db.url=jdbc:mysql://192.168.182.135:3306/bank db.driver=com.mysql.jdbc.Driver db.user=root db.password=123456 #数据库连接池配置 #连接池中保留的最小连接数 pool.minPoolSize=5 #连接池中保留的最大连接数 pool.maxPoolSize=30 #获取连接超时时间 pool.checkoutTimeout=1000
配置 servlet.xml, 由WebConfig类实现
Thymeleaf 模板配置也在下面
1 package com.liulu.bank.config; 2 3 import org.springframework.context.annotation.Bean; 4 import org.springframework.context.annotation.ComponentScan; 5 import org.springframework.context.annotation.Configuration; 6 import org.springframework.stereotype.Controller; 7 import org.springframework.web.servlet.ViewResolver; 8 import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; 9 import org.springframework.web.servlet.config.annotation.EnableWebMvc; 10 import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 11 import org.thymeleaf.TemplateEngine; 12 import org.thymeleaf.spring4.SpringTemplateEngine; 13 import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver; 14 import org.thymeleaf.spring4.view.ThymeleafViewResolver; 15 import org.thymeleaf.templatemode.TemplateMode; 16 17 import java.nio.charset.StandardCharsets; 18 19 /** 20 * User : liulu 21 * Date : 2016-10-7 15:16 22 */ 23 @Configuration 24 @EnableWebMvc // 启用 SpringMVC ,相当于 xml中的 <mvc:annotation-driven/> 25 @ComponentScan(basePackages = {"com.liulu.bank.controller", "com.liulu.lit"}, 26 includeFilters = @ComponentScan.Filter(classes = Controller.class), 27 useDefaultFilters = false) 28 public class WebConfig extends WebMvcConfigurerAdapter { 29 30 /** 31 * 设置由 web容器处理静态资源 ,相当于 xml中的<mvc:default-servlet-handler/> 32 */ 33 @Override 34 public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { 35 configurer.enable(); 36 } 37 38 /** 39 * 下面三个bean 配置 Thymeleaf 模板 40 * @return 41 */ 42 @Bean 43 public SpringResourceTemplateResolver templateResolver() { 44 SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver(); 45 templateResolver.setPrefix("/WEB-INF/templates/"); 46 templateResolver.setSuffix(".html"); 47 templateResolver.setTemplateMode(TemplateMode.HTML); 48 templateResolver.setCharacterEncoding(String.valueOf(StandardCharsets.UTF_8)); 49 return templateResolver; 50 } 51 52 @Bean 53 public TemplateEngine templateEngine(SpringResourceTemplateResolver templateResolver) { 54 SpringTemplateEngine templateEngine = new SpringTemplateEngine(); 55 templateEngine.setTemplateResolver(templateResolver); 56 return templateEngine; 57 } 58 59 @Bean 60 public ViewResolver viewResolver(TemplateEngine templateEngine) { 61 ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); 62 viewResolver.setTemplateEngine(templateEngine); 63 viewResolver.setCharacterEncoding(String.valueOf(StandardCharsets.UTF_8)); 64 return viewResolver; 65 } 66 67 }