# springboot项目搭建学习
**Repository Path**: xttup/springbootxiangmudajianxuexi
## Basic Information
- **Project Name**: springboot项目搭建学习
- **Description**: springboot项目开发所常用的一些功能示例
- **Primary Language**: Java
- **License**: Not specified
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 2
- **Forks**: 1
- **Created**: 2017-05-29
- **Last Updated**: 2020-12-19
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
1.创建springboot项目
1)使用idea - create new project - Spring initializr
2)选用项目使用技术,Session ,sping-validation,spring-retry, Aop ,cache ...
2.配置application.properties 或使用yml文件方法配置
1)基本配置:
server.port=80 //设置80端口
server.context-path=/springboot //设置项目路径
。。
2)属性注入:
2.1)基本类型
uploadfile : d://upload --controller中 : @Value("${uploadfile}")
基本类型自动转换
2.1)注入对象
导入依赖:
org.springframework.boot
spring-boot-configuration-processor
true
建立实体类:Example.class
类注解@Component 注入容器,
@ConfigurationProperties(prefix = "example") 指定配置属性
@Autowired 注入
3)指定开发环境和生产环境配置文件
新建application-dev.yml 和application-prod.yml配置文件
在application中指定spring.properties.active:dev(开发)
3.controller 注解
1)@RestController = @Controler + @ResponseBody
2) @PathVariable("id")
2)模板使用。。。略
4.操作数据库
1)导入依赖
org.springframework.boot
spring-boot-starter-data-jpa
mysql
mysql-connector-java
2) application-dev.yml 配置数据库连接 和jpa
spring:
#数据库连接属性配置
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/springboot
username: root
password: root
#jpa属性配置
jpa:
hibernate:
ddl-auto: update # create 每次创建,validate 验证,不一致报错,create-drop:运行停止时删除表
show-sql: true
3)data-jpa 基本操作
可参见 http://blog.csdn.net/linzhiqiang0316/article/details/52639265
4) 数据库连接池druid
1.引入依赖
com.alibaba
druid
1.0.18
2.配置数据源相关信息 application-dev.yml
3.由于Druid暂时不在Spring Boot中的直接支持,故需要进行配置信息的定制:DruidDBConfig.class
3.配置监控统计功能
配置servlet DruidStatViewServlet.class
配置filter DruidStatFilter.class
(
springboot filter listener servlet 有两种配置方式,
一、为采用原生Servlet3.0的注解进行配置、@WebServlet 、@WebListener、@WebFilter是Servlet3.0 api中提供的注解
见DruidStatFilter.java、DruidStatViewServlet.java
二、springboot 提供bean 配置方式 FilterRegistrationBean、ServletRegistrationBean、ServletListenerRegistrationBean)
见DruiDBconfig.java
5.springboot 启动类SpringbootApplication.class加上注解@ServletComponentScan使其能扫描到servlet 和filter
6.访问http://127.0.0.1/springboot/druid/index.html 查看监控统计
7.访问http://127.0.0.1/springboot/druid/sql.html 查看sql性能
5.事务
方法或类上加入注解@Transactional
6.aop
例: AopExample.class
7.全局异常处理
建立全局异常处理类 ExceptionHandle.class
8.注解方式过滤器监听器
1).过滤器:(过滤器顺序--想要控制filer的执行顺序可以通过控制filter的文件名来控制??)
例:MyFilter.class
2).监听器 MyListener.class
9.拦截器
1).创建拦截处理类,LoginInterceptor.class 实现HandlerInterceptor接口,写入拦截逻辑
2).创建MyWebMvcConfigAdapter.class继承WebMvcConfigurerAdapter类,
类头注解@Configuration
重写addInterceptors 方法,添加自定义拦截器
注:resources 下static 和templates 文件夹默认不拦截,如需添加其他静态资源路径
重写addResourceHandlers方法
10.日期转换处理
前端字符串传入后端,实体类对应属性添加@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
如:前台传入为String 2017-05-29 17:38:26
后端传入前端,实体类对应属性添加@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
如:从数据库查出的日期需要在前端展示为2017-05-29 17:38:26
例:User.class
11.校验
例: UserController.class
约束注解名称 约束注解说明
@NotEmpty
@Length
@null 验证对象是否为空
@notnull 验证对象是否为非空
@asserttrue 验证 boolean 对象是否为 true
@assertfalse 验证 boolean 对象是否为 false
@min 验证 number 和 string 对象是否大等于指定的值
@max 验证 number 和 string 对象是否小等于指定的值
@decimalmin 验证 number 和 string 对象是否大等于指定的值,小数存在精度
@decimalmax 验证 number 和 string 对象是否小等于指定的值,小数存在精度
@size 验证对象(array,collection,map,string)长度是否在给定的范围之内
@digits 验证 number 和 string 的构成是否合法
@past 验证 date 和 calendar 对象是否在当前时间之前
@future 验证 date 和 calendar 对象是否在当前时间之后
@pattern 验证 string 对象是否符合正则表达式的规则
@Email 验证邮箱
12.task定时任务
1.创建定时任务 TaskExample.class,类上注解@Component 方法上注解@Scheduled(cron="0/2 * * * * ?")
2.springboot SpringbootApplication.class启动类上注解@EnableScheduling
13.重试spring-retry
1.导入依赖
org.springframework.retry
spring-retry
2.对需要异常重试方法加入注解 (RetryExampleImpl.class)
@Retryable(value = {AppException.class},maxAttempts = 4,backoff = @Backoff(delay = 1000, multiplier = 1))
注:
@Retryable注解
被注解的方法发生异常时会重试
value:指定发生的异常进行重试
include:和value一样,默认空,当exclude也为空时,所有异常都重试
exclude:指定异常不重试,默认空,当include也为空时,所有异常都重试
maxAttemps:重试次数,默认3
backoff:重试补偿机制,默认没有
@Backoff注解
delay:指定延迟后重试
multiplier:指定延迟的倍数,比如delay=5000l,multiplier=2时,第一次重试为5秒后,第二次为10秒,第三次为20秒
@Recover
当重试到达指定次数时,被注解的方法将被回调,可以在该方法中进行日志处理。需要注意的是发生的异常和入参类型一致时才会回调
3.在启动类中SpringbootApplication.class加入注解
@EnableRetry
14.热部署
idea:->https://www.cnblogs.com/asis/p/spring-boot-hot-swap.html
1.添加依赖
org.springframework.boot
spring-boot-devtools
true
2.打开 Settings --> Build-Execution-Deployment --> Compiler,将 Build project automatically.勾上。
3.点击 Help --> Find Action..,或使用快捷键 Ctrl+Shift+A来打开 Registry...,将 其中的compiler.automake.allow.when.app.running勾上。
15.redis 配置
->http://projects.spring.io/spring-data-redis/
spring-data-redis 使用样例官方推荐-> http://github.com/spring-projects/spring-data-keyvalue-examples
(本地安装测试redis)
1.引入依赖
org.springframework.boot
spring-boot-starter-data-redis
2.application-dev.yml配置redis相关参数
3.使用见RedisService
4.spring-data-redis提供两种template
1.RedisTemplate:使用JdkSerializationRedisSerializer
存储对象需要实现序列化接口
2.StringRedisTemplate:使用.StringRedisSerializer
用与存储一般的String
3.spring-data-redis的序列化类有下面这几个:
GenericToStringSerializer: 可以将任何对象泛化为字符串并序列化
Jackson2JsonRedisSerializer: 跟JacksonJsonRedisSerializer实际上是一样的
JacksonJsonRedisSerializer: 序列化object对象为json字符串,不需要实现序列化【需要jackson-mapper-asl工具支持】
JdkSerializationRedisSerializer: 序列化java对象
StringRedisSerializer: 简单的字符串序列化
OxmSerializer:存储数据为xml【需要spring-oxm模块的支持】
5.redis事务
两种方式使用:
1.通过SessionCallback 接口执行事务
->见RedisService actInTransaction
->RedisServiceTest testTransac
2.redis事务默认为关闭的,设置setEnableTransactionSupport(true)开启
setEnableTransactionSupport配置方式:
1.->RedisConfig.java,使用自定义配置RedisConfig,
yml中设置的redis配置需要自己配置入JedisConnectionFactory,否则yml中的配置不会生效,会使用默认配置
2.->RedisConfig2.java
@AutoConfigureAfter(RedisAutoConfiguration.class)
通过AutoConfigureAfter注解,在自动配置完成之后,取得自动配置的redisTemplate
增加一些自定义配置,在通过@Bean替换掉redisTempate
3.获取在使用时redisTempate.setEnableTransactionSupport(true)
使用@Transactional注解
->见RedisService actInTransaction2
->RedisServiceTest testTransac2
6.Pipelining 管道...(不具备原子性)
->https://docs.spring.io/spring-data/data-redis/docs/current/reference/html/#pipeline
7.script 脚本...
->https://docs.spring.io/spring-data/data-redis/docs/current/reference/html/#scripting
16.logging 日志
1.spring 内部使用Commons logging
spring boot使用Logback作为日志实现的框架。
maven无需额外添加spring-boot-starter-logging,默认已经添加该依赖
日志级别:
TRACE < DEBUG < INFO < WARN < ERROR < FATAL
2.application.yml配置
logging:
file: springboot.log
level:
com:
xtt: debug
默认日志达10M,会生成新的日志
'logging.level.* = LEVEL' 可以指定文件或日志名的输出级别
logging.pattern.console:定义输出到控制台的样式(不支持JDK Logger)
logging.pattern.file 定义输出到文件的样式(不支持JDK Logger)
3.日志配置扩展
logging:
config: classpath:config/logback-spring.xml
4.其他日志配置:
1.根据不同的日志系统,你可以按如下规则组织配置文件名,就能被正确加载:
Logback:logback-spring.xml, logback-spring.groovy, logback.xml, logback.groovy
Log4j:log4j-spring.properties, log4j-spring.xml, log4j.properties, log4j.xml
Log4j2:log4j2-spring.xml, log4j2.xml
JDK (Java Util Logging):logging.properties
2.如需自定义文件名(logging-config.xml):
logging.config=classpath:logging-config.xml