本博客大概会介绍在Springboot开发过程中所遇到的各种问题以及各种工具的配置。
1、多项目搭建以及配置:首先建立空的Maven项目作为父项目,然后在父项目中new一个module(即子项目模块),各个子项目通过
2、@MapperScan注解:该注解定位到Dao层接口中,使用该注解后可以起到各个Dao层类中的@Mapper的效果,省去麻烦。
3、C3P0连接池配置:
properties代码:
#c3p0
c3p0.jdbcUrl=jdbc:mysql://localhost:3306/cmsystem?useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false&useSSL=false&useAffectedRows=true&serverTimezone=UTC
c3p0.user=root
c3p0.password=root
c3p0.driverClass=com.mysql.cj.jdbc.Driver
c3p0.minPoolSize=2
c3p0.maxPoolSize=10
c3p0.maxIdleTime=1800000
c3p0.acquireIncrement=3
c3p0.maxStatements=1000
c3p0.initialPoolSize=3
c3p0.idleConnectionTestPeriod=60
c3p0.acquireRetryAttempts=30
c3p0.acquireRetryDelay=1000
c3p0.breakAfterAcquireFailure=false
c3p0.testConnectionOnCheckout=true
在 启动类同目录下配置注解类:
@Configuration
public class DatasourceConfiguration {
@Bean(name = "dataSource")
@Qualifier(value = "dataSource")
@Primary
@ConfigurationProperties(prefix = "c3p0")
public DataSource dataSource(){
return DataSourceBuilder.create().type(com.mchange.v2.c3p0.ComboPooledDataSource.class).build();
}
}
4、Redis配置:
将redis安装为windows服务,并启动
properties配置:
# REDIS (RedisProperties)
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=-1
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=200
5、开启简答事务:在主启动类添加@EnableTransactionManagement注解,在Service层方法上开启@Transactional注解
6、Thymeleaf和mybatis配置:引入相关jar包,priperties中:
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.cache=false
mybatis.mapper-locations = classpath:mybatis/*.xml
mybatis.type-aliases-package = com.entity
7、SpringBoot错误页面配置:主启动类目录下新建类:
@Component
public class ErrorPageConfig implements ErrorPageRegistrar{
@Override
public void registerErrorPages(ErrorPageRegistry registry) {
ErrorPage e404 = new ErrorPage(HttpStatus.NOT_FOUND, "/error/404");
// TODO Auto-generated method stub
ErrorPage e500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500");
registry.addErrorPages(e404, e500);
}
}
8、文件上传和下载:
/**
* 文件上传配置
* @return
*/
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
//单个文件最大
factory.setMaxFileSize("20MB"); //KB,MB
/// 设置总上传数据总大小
//factory.setMaxRequestSize("102400KB");
return factory.createMultipartConfig();
}
上传文件:Controller中使用@RequestParam(value = "file", required = false)MultipartFile file 参数接收文件,使用file.transferTo(tagetFile);进行文件复制保存。
下载文件:方法如下所示:
public static void downloadFile(String url, HttpServletResponse response) {
// TODO Auto-generated method stub
File file = new File(url);
String[] temp = url.split(File.separator+File.separator);
String fileName = temp[temp.length-1];
FileInputStream fis = null;
if (file.exists()) {
try {
response.reset();
response.setHeader("Content-Disposition", "attachment; filename="+new String(fileName.getBytes(),"iso-8859-1"));
response.setContentType("application/octet-stream; charset=utf-8");
fis = new FileInputStream(file);
byte[] buffer = new byte[128];
int count = 0;
while ((count = fis.read(buffer)) > 0) {
response.getOutputStream().write(buffer, 0, count);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
response.getOutputStream().flush();
response.getOutputStream().close();
if (fis != null) {
fis.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
9、统一接口返回:
RetCode.java
public enum RetCode {
// 成功
SUCCESS(200),
// 失败
FAIL(400),
// 未认证(签名错误)
UNAUTHORIZED(401),
// 接口不存在
NOT_FOUND(404),
// 服务器内部错误
INTERNAL_SERVER_ERROR(500);
public int code;
RetCode(int code) {
this.code = code;
}
}
RetResult.java
public class RetResult
public int code;
private String msg;
private T data;
public RetResult
this.code = retCode.code;
return this;
}
public int getCode() {
return code;
}
public RetResult
this.code = code;
return this;
}
public String getMsg() {
return msg;
}
public RetResult
this.msg = msg;
return this;
}
public T getData() {
return data;
}
public RetResult
this.data = data;
return this;
}
}
RetResponse.java
public class RetResponse {
public static
return new RetResult
}
public static
return new RetResult
}
public static
return new RetResult
}
public static
return new RetResult
}
public static
return new RetResult
}
public static
return new RetResult
}
}
10、后台处理跨域问题
@Configuration
public class PassUrl {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 1允许任何域名使用
corsConfiguration.addAllowedHeader("*"); // 2允许任何头
corsConfiguration.addAllowedMethod("*"); // 3允许任何方法(post、get等)
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 4
return new CorsFilter(source);
}
}