前言
Spring Boot 是由 Pivotal 團(tuán)隊(duì)提供的全新框架,其設(shè)計(jì)目的是用來簡(jiǎn)化新 Spring 應(yīng)用的初始搭建以及開發(fā)過程。該框架使用了特定的方式來進(jìn)行配置,從而使開發(fā)人員不再需要定義樣板化的配置。
正好公司最近做一個(gè)新項(xiàng)目,就考慮把原來的傳統(tǒng)框架改造成Spring Boot的框架,以下為改造過程記錄。
1.修改pom.xml依賴
Spring Boot工程的父依賴必須為spring-boot-starter-parent,而且它引入的依賴也相當(dāng)簡(jiǎn)潔,如下所示:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
Spring Boot 2 JDK必須至少為1.8,Tomcat為7.0.78,Redis本地為3.2.9(現(xiàn)網(wǎng)為2.8.3)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
<!-- 內(nèi)嵌的Tomcat不需排除 -->
<!-- <exclusion>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</exclusion> -->
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!-- 私服上的JAR包有問題 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<scope>system</scope>
<systemPath>${basedir}/lib/jedis-2.9.0.jar</systemPath>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
添加web,mybatis和redis支持,去除內(nèi)嵌的tomcat以及默認(rèn)的log,采用log4j2。另外,私服上的jedis包有問題,雖然看源代碼沒有問題,但實(shí)際的jar是有問題的,最后從公服上下了jar,放在lib下,直接引用。
<!-- hibernate-validator降級(jí),解決ELManager找不到的問題(內(nèi)嵌的Tomcat忽略此問題) -->
<!-- <dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.3.6.Final</version>
</dependency> -->
<build>
<finalName>familydoctor-webapp-v2</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.4.2.RELEASE</version>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
</build>
2.修改配置文件
這也是本次改造工程的關(guān)鍵,修改前的配置文件如下所示:

2.1新增FamilyDoctorApplication
FamilyDoctorApplication是Spring Boot的入口文件,該文件一般放在包的根目錄下,代碼如下:
package com.asiainfo.aigov;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@SpringBootApplication
public class FamilyDoctorApplication extends SpringBootServletInitializer {
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(FamilyDoctorApplication.class);
}
}
2.2刪除web.xml
2.3刪除applicationContext-mvc.xml,新增MyMvcConfigurer
之所以選擇實(shí)現(xiàn)WebMvcConfigurer,而不是選擇繼承WebMvcConfigurationSupport,是因?yàn)槔^承WebMvcConfigurationSupport會(huì)導(dǎo)致原先默認(rèn)的自動(dòng)配置無效,而實(shí)現(xiàn)WebMvcConfigurer只會(huì)新增新的配置,不會(huì)使原先默認(rèn)的自動(dòng)配置無效。
MyMvcConfigurer如下所示:
package com.asiainfo.aigov.config;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.asiainfo.aigov.system.interceptor.AppUserInterceptor;
import com.asiainfo.aigov.system.resolver.UserSessionArgumentResolver;
import com.asiainfo.aigov.system.web.servlet.InitServlet;
import com.asiainfo.aigov.system.web.session.UserSessionFilter;
import com.asiainfo.frame.servlet.ImageServlet;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 代替原先的applicationContext-mvc.xml
* @author pany
*
*/
@Configuration
@EnableAspectJAutoProxy
public class MyMvcConfigurer implements WebMvcConfigurer {
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new UserSessionArgumentResolver());
}
@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
ObjectMapper objectMapper = new ObjectMapper();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
objectMapper.setDateFormat(sdf);
converter.setObjectMapper(objectMapper);
converter.setSupportedMediaTypes(Lists.newArrayList(MediaType.TEXT_HTML, MediaType.APPLICATION_JSON_UTF8, MediaType.APPLICATION_FORM_URLENCODED));
return converter;
}
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(mappingJackson2HttpMessageConverter());
}
@Bean
public InternalResourceViewResolver internalResourceViewResolver() {
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
internalResourceViewResolver.setPrefix("/WEB-INF/views/");
internalResourceViewResolver.setSuffix(".jsp");
return internalResourceViewResolver;
}
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.viewResolver(internalResourceViewResolver());
}
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new AppUserInterceptor());
}
/**
* 默認(rèn)的/**是映射到/static,需改成/
*/
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("/");
// /META-INF/resources/下的資源可以直接讀取,但為了兼容舊的/resources/寫法,需做以下配置
registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/META-INF/resources/");
}
@Bean
public FilterRegistrationBean<UserSessionFilter> userSessionFilter() {
FilterRegistrationBean<UserSessionFilter> userSessionFilter = new FilterRegistrationBean<>(new UserSessionFilter());
userSessionFilter.addUrlPatterns("/*");
userSessionFilter.setOrder(1);
return userSessionFilter;
}
@Bean
public FilterRegistrationBean<WebStatFilter> webStatFilter() {
FilterRegistrationBean<WebStatFilter> webStatFilter = new FilterRegistrationBean<>(new WebStatFilter());
webStatFilter.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
webStatFilter.addUrlPatterns("/*");
webStatFilter.setOrder(2);
return webStatFilter;
}
@Bean
public ServletRegistrationBean<InitServlet> initServlet() {
ServletRegistrationBean<InitServlet> initServlet = new ServletRegistrationBean<>(new InitServlet(), false);
initServlet.setLoadOnStartup(1);
return initServlet;
}
@Bean
public ServletRegistrationBean<StatViewServlet> statViewServlet() {
ServletRegistrationBean<StatViewServlet> statViewServlet = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
return statViewServlet;
}
@Bean
public ServletRegistrationBean<ImageServlet> imageServlet() {
ServletRegistrationBean<ImageServlet> imageServlet = new ServletRegistrationBean<>(new ImageServlet(), "/imageServlet");
Map<String, String> initParameters = new HashMap<>();
initParameters.put("imgWidth", "120");
initParameters.put("imgHeight", "48");
initParameters.put("codeCount", "4");
initParameters.put("fontStyle", "Times New Roman");
imageServlet.setInitParameters(initParameters);
return imageServlet;
}
}
2.4新增application.properties
包含數(shù)據(jù)源與Redis配置,刪除對(duì)應(yīng)的配置文件(applicationContext-mybatis-oracle.xml、applicationContext-mybatis.xml、applicationContext-redis.xml、applicationContext.xml、db.properties)
spring.datasource.oracle.url=jdbc:oracle:thin:@10.63.80.240:1521:devdb
spring.datasource.oracle.username=familydoctor
spring.datasource.oracle.password=f2r22s2_c33Srfrmm
spring.datasource.oracle.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.redis.host=127.0.0.1
spring.redis.port=6379
server.servlet.context-path=/familydoctor-webapp
server.port=8080
#server.servlet.session.timeout=60 會(huì)話超時(shí)時(shí)間,最小為60秒
logging.level.root=INFO 不使用log4j2,采用默認(rèn)的日志并設(shè)置級(jí)別
# 屏蔽o.a.tomcat.util.scan.StandardJarScanner : Failed to scan錯(cuò)誤
logging.level.org.apache.tomcat.util.scan.StandardJarScanner=ERROR
# 相對(duì)路徑,默認(rèn)輸出的日志文件名為spring.log
#logging.path=log
spring.profiles.active=dev
#debug=true
2.5新增OracleDSConfig
數(shù)據(jù)源采用Java Config配置
package com.asiainfo.aigov.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import com.alibaba.druid.pool.DruidDataSource;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = "com.asiainfo.aigov.**.dao", sqlSessionTemplateRef = "oracleSqlSessionTemplate")
public class OracleDSConfig {
@Value("${spring.datasource.oracle.url}")
private String url;
@Value("${spring.datasource.oracle.username}")
private String username;
@Value("${spring.datasource.oracle.password}")
private String password;
@Value("${spring.datasource.oracle.driver-class-name}")
private String driverClassName;
@Bean
@Primary
public DataSource oracleDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setDriverClassName(driverClassName);
return dataSource;
}
@Bean
@Primary
public SqlSessionFactory oracleSqlSessionFactory(@Qualifier("oracleDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:sqlMapConfig-oracle.xml"));
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:com/asiainfo/aigov/**/oracle/*Mapper.xml"));
return bean.getObject();
}
@Bean
@Primary
public DataSourceTransactionManager oracleTransactionManager(@Qualifier("oracleDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean
@Primary
public SqlSessionTemplate oracleSqlSessionTemplate(@Qualifier("oracleSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
@Bean
@Primary
public JdbcTemplate jdbcTemplate(@Qualifier("oracleDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
2.6覆蓋RedisGenerator
Spring Boot默認(rèn)配置的RedisTemplate有兩個(gè),一個(gè)是RedisTemplate,一個(gè)是StringRedisTemplate,我們使用的是RedisTemplate。之所以要覆蓋,是因?yàn)樵鹊膕pring-session-data-redis是1.2.2.RELEASE版本,而Spring Boot 2的是2.0.2.RELEASE版本。這樣的話,原先編譯出來的RedisGenerator里的redisTemplate的delete方法的簽名和Spring Boot 2就會(huì)不一致,從而導(dǎo)致調(diào)用的時(shí)候報(bào)錯(cuò)。
Java類調(diào)用的方法的簽名是編譯的時(shí)候就確定的,所以編譯的版本要和運(yùn)行的版本一致。
package com.asiainfo.aigov.system.cache;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import com.asiainfo.frame.utils.ApplicationContextUtil;
public class RedisGenerator {
private RedisTemplate<String, Object> redisTemplate;
private ValueOperations<String, Object> valueOps;
protected static RedisGenerator redisGenerator = null;
public static RedisGenerator getInstance() {
if (redisGenerator == null) {
redisGenerator = new RedisGenerator();
}
return redisGenerator;
}
@SuppressWarnings("unchecked")
private RedisGenerator() {
this.redisTemplate = (RedisTemplate<String, Object>)ApplicationContextUtil.getInstance().getBean("redisTemplate");
this.valueOps = this.redisTemplate.opsForValue();
}
/**
* @param key
* @return
*/
public Object get(String key) {
return this.valueOps.get(key);
}
/**
* @param key
* @param value
*/
public void add(String key, Object value) {
this.valueOps.set(key, value);
}
/**
* @param key
*/
public void remove(String key) {
this.redisTemplate.delete(key);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public void removeAll() {
// 刪除當(dāng)前數(shù)據(jù)庫(kù)中的所有Key
// flushdb
this.redisTemplate.execute(new RedisCallback() {
public String doInRedis(RedisConnection connection) throws DataAccessException {
connection.flushDb();
return "ok";
}
});
}
}
2.7日志管理
原先代碼是采用log4j來寫日志,而Spring Boot 2不支持log4j,支持的是log4j2。為了讓新舊日志都能打印,加入log4j2.xml。同時(shí),Tomcat的啟動(dòng)參數(shù)為增加-Djavax.xml.parsers.DocumentBuilderFactory="com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl",以免剛開始啟動(dòng)的時(shí)候會(huì)報(bào)錯(cuò)。
打印日志的時(shí)候要用org.apache.commons.logging提供的日志類,這樣無論是用log4j還是log4j2,都可以打印出日志。代碼如下:
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
private static Log logger = LogFactory.getLog(InitServlet.class);

log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--日志級(jí)別以及優(yōu)先級(jí)排序: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->
<!--Configuration后面的status,這個(gè)用于設(shè)置log4j2自身內(nèi)部的信息輸出,可以不設(shè)置,當(dāng)設(shè)置成trace時(shí),你會(huì)看到log4j2內(nèi)部各種詳細(xì)輸出 -->
<!--monitorInterval:Log4j能夠自動(dòng)檢測(cè)修改配置 文件和重新配置本身,設(shè)置間隔秒數(shù) -->
<configuration status="INFO" monitorInterval="30">
<!--先定義所有的appender -->
<appenders>
<!--這個(gè)輸出控制臺(tái)的配置 -->
<console name="Console" target="SYSTEM_OUT">
<ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY" />
<PatternLayout pattern="[%-5p] [%d{yyyy-MM-dd HH:mm:ss}] %c:%L - %m%n" />
</console>
<!-- 這個(gè)會(huì)打印出所有的info及以下級(jí)別的信息,每次大小超過size,則這size大小的日志會(huì)自動(dòng)存入按年份-月份建立的文件夾下面并進(jìn)行壓縮,作為存檔 -->
<RollingFile name="RollingFileDebug" fileName="/Users/pany/Documents/logs/debug.log" filePattern="/Users/pany/Documents/logs/debug.log.%d{yyyy-MM-dd}">
<!--控制臺(tái)只輸出level及以上級(jí)別的信息(onMatch),其他的直接拒絕(onMismatch) -->
<ThresholdFilter level="debug" onMatch="ACCEPT" onMismatch="DENY" />
<PatternLayout pattern="[%-5p] [%d{yyyy-MM-dd HH:mm:ss}] %c:%L - %m%n" />
<Policies>
<TimeBasedTriggeringPolicy />
</Policies>
</RollingFile>
<RollingFile name="RollingFileInfo" fileName="/Users/pany/Documents/logs/info.log" filePattern="/Users/pany/Documents/logs/info.log.%d{yyyy-MM-dd}">
<ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY" />
<PatternLayout pattern="[%-5p] [%d{yyyy-MM-dd HH:mm:ss}] %c:%L - %m%n" />
<Policies>
<TimeBasedTriggeringPolicy />
</Policies>
</RollingFile>
<RollingFile name="RollingFileError" fileName="/Users/pany/Documents/logs/error.log" filePattern="/Users/pany/Documents/logs/error.log.%d{yyyy-MM-dd}">
<ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY" />
<PatternLayout pattern="[%-5p] [%d{yyyy-MM-dd HH:mm:ss}] %c:%L - %m%n" />
<Policies>
<TimeBasedTriggeringPolicy />
</Policies>
</RollingFile>
</appenders>
<!--然后定義logger,只有定義了logger并引入的appender,appender才會(huì)生效 -->
<loggers>
<!--過濾掉spring和mybatis的一些無用的DEBUG信息 -->
<logger name="org.springframework" level="INFO"></logger>
<logger name="org.mybatis" level="INFO"></logger>
<root level="all">
<appender-ref ref="Console" />
<!-- <appender-ref ref="RollingFileDebug" /> -->
<!-- <appender-ref ref="RollingFileInfo" /> -->
<!-- <appender-ref ref="RollingFileError" /> -->
</root>
</loggers>
</configuration>
3.結(jié)束語(yǔ)
修改后的配置文件如下所示:

和原來相比減少了6個(gè)配置文件,因?yàn)槭歉脑炖峡蚣?,為了兼容,還是留下了部分的配置文件(如app.properties、caches.properties等)。
另外,在改造的過程中有出現(xiàn)訪問JSP頁(yè)面白屏的問題,后面發(fā)現(xiàn)ServletRegistrationBean和FilterRegistrationBean的默認(rèn)urlMappings都是/*,像InitServlet這樣如果注冊(cè)的時(shí)候沒有配urlMappings,而實(shí)際上它的urlMappings就默認(rèn)為/*,這樣就會(huì)把原先映射到DispatcherServlet的請(qǐng)求映射到InitServlet上,從而導(dǎo)致頁(yè)面白屏。解決方法是在創(chuàng)建ServletRegistrationBean的時(shí)候設(shè)置alwaysMapUrl為false。
ServletRegistrationBean<InitServlet> initServlet = new ServletRegistrationBean<>(new InitServlet(), false);
最終工程啟動(dòng)成功,登錄和退出也正常,改造工作算是告一段落。