你的位置:首页 > Java教程

[Java教程]Spring MVC 完全注解方式配置web项目


    在 servlet 3.0 开始web项目可以完全不需要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.

getServletConfigClasses()获取配置类,相当于 mvc-servlet.

此类上不需要任何注解,

 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 : liulu14  * Date : 2016-10-7 15:1215 */16 public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer implements WebApplicationInitializer {17 18   @Override19   protected Class<?>[] getRootConfigClasses() {20     return new Class<?>[]{RootConfig.class};21   }22 23   @Override24   protected Class<?>[] getServletConfigClasses() {25     return new Class<?>[]{WebConfig.class};26   }27 28   /**29    * 配置DispatcherServlet 匹配的路径30    * @return31   */32   @Override33   protected String[] getServletMappings() {34     return new String[]{"/"};35   }36 37   /**38    * 配置其他的 servlet 和 filter39    *40    * @param servletContext41    * @throws ServletException42   */43   @Override44   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.
 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 : liulu18  * Date : 2016-10-7 15:3619 */20 @Configuration21 @PropertySource("classpath:config.properties") // 导入属性文件22 @EnableAspectJAutoProxy // 相当于 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   @Resource29   private Environment env;30 31   /**32    * 配置数据库连接池 c3p0,33    * @return34    * @throws PropertyVetoException35   */36   @Bean37   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 dataSource54    * @return55   */56   @Bean57   public PlatformTransactionManager transactionManager(DataSource dataSource) {58     return new DataSourceTransactionManager(dataSource);59   }60 61   @Bean62   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/bankdb.driver=com.mysql.jdbc.Driverdb.user=rootdb.password=123456#数据库连接池配置#连接池中保留的最小连接数pool.minPoolSize=5#连接池中保留的最大连接数pool.maxPoolSize=30#获取连接超时时间pool.checkoutTimeout=1000

 

 配置 servlet.

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 : liulu21  * Date : 2016-10-7 15:1622 */23 @Configuration24 @EnableWebMvc // 启用 SpringMVC ,相当于 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容器处理静态资源 ,相当于 32   */33   @Override34   public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {35     configurer.enable();36   }37 38   /**39    * 下面三个bean 配置 Thymeleaf 模板40    * @return41   */42   @Bean43   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   @Bean53   public TemplateEngine templateEngine(SpringResourceTemplateResolver templateResolver) {54     SpringTemplateEngine templateEngine = new SpringTemplateEngine();55     templateEngine.setTemplateResolver(templateResolver);56     return templateEngine;57   }58 59   @Bean60   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 }