前言
Spring Boot 是由 Pivotal 团队提供的全新框架,其设计目的是用来简化新 Spring 应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。
正好公司最近做一个新项目,就考虑把原来的传统框架改造成Spring Boot的框架,以下为改造过程记录。
1.修改pom.xml依赖
Spring Boot工程的父依赖必须为spring-boot-starter-parent,而且它引入的依赖也相当简洁,如下所示:
<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(现网为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>
<!-- 内嵌的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支持,去除内嵌的tomcat以及默认的log,采用log4j2。另外,私服上的jedis包有问题,虽然看源代码没有问题,但实际的jar是有问题的,最后从公服上下了jar,放在lib下,直接引用。
<!-- hibernate-validator降级,解决ELManager找不到的问题(内嵌的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.修改配置文件
这也是本次改造工程的关键,修改前的配置文件如下所示:
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
之所以选择实现WebMvcConfigurer,而不是选择继承WebMvcConfigurationSupport,是因为继承WebMvcConfigurationSupport会导致原先默认的自动配置无效,而实现WebMvcConfigurer只会新增新的配置,不会使原先默认的自动配置无效。
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());
}
/**
* 默认的/**是映射到/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
包含数据源与Redis配置,删除对应的配置文件(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 会话超时时间,最小为60秒
logging.level.root=INFO 不使用log4j2,采用默认的日志并设置级别
# 屏蔽o.a.tomcat.util.scan.StandardJarScanner : Failed to scan错误
logging.level.org.apache.tomcat.util.scan.StandardJarScanner=ERROR
# 相对路径,默认输出的日志文件名为spring.log
#logging.path=log
spring.profiles.active=dev
#debug=true
2.5新增OracleDSConfig
数据源采用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默认配置的RedisTemplate有两个,一个是RedisTemplate,一个是StringRedisTemplate,我们使用的是RedisTemplate。之所以要覆盖,是因为原先的spring-session-data-redis是1.2.2.RELEASE版本,而Spring Boot 2的是2.0.2.RELEASE版本。这样的话,原先编译出来的RedisGenerator里的redisTemplate的delete方法的签名和Spring Boot 2就会不一致,从而导致调用的时候报错。
Java类调用的方法的签名是编译的时候就确定的,所以编译的版本要和运行的版本一致。
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() {
// 删除当前数据库中的所有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。同时,Tomcat的启动参数为增加-Djavax.xml.parsers.DocumentBuilderFactory="com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl",以免刚开始启动的时候会报错。
打印日志的时候要用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"?>
<!--日志级别以及优先级排序: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->
<!--Configuration后面的status,这个用于设置log4j2自身内部的信息输出,可以不设置,当设置成trace时,你会看到log4j2内部各种详细输出 -->
<!--monitorInterval:Log4j能够自动检测修改配置 文件和重新配置本身,设置间隔秒数 -->
<configuration status="INFO" monitorInterval="30">
<!--先定义所有的appender -->
<appenders>
<!--这个输出控制台的配置 -->
<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>
<!-- 这个会打印出所有的info及以下级别的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档 -->
<RollingFile name="RollingFileDebug" fileName="/Users/pany/Documents/logs/debug.log" filePattern="/Users/pany/Documents/logs/debug.log.%d{yyyy-MM-dd}">
<!--控制台只输出level及以上级别的信息(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才会生效 -->
<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.结束语
修改后的配置文件如下所示:
和原来相比减少了6个配置文件,因为是改造老框架,为了兼容,还是留下了部分的配置文件(如app.properties、caches.properties等)。
另外,在改造的过程中有出现访问JSP页面白屏的问题,后面发现ServletRegistrationBean和FilterRegistrationBean的默认urlMappings都是/*
,像InitServlet这样如果注册的时候没有配urlMappings,而实际上它的urlMappings就默认为/*
,这样就会把原先映射到DispatcherServlet的请求映射到InitServlet上,从而导致页面白屏。解决方法是在创建ServletRegistrationBean的时候设置alwaysMapUrl为false。
ServletRegistrationBean<InitServlet> initServlet = new ServletRegistrationBean<>(new InitServlet(), false);
最终工程启动成功,登录和退出也正常,改造工作算是告一段落。