spring boot 项目搭建
基础
- 位置
- MainApplication放在主包下面,会自动扫描当前包以及当前包的子包
server:
port: 8080
数据库集成
基础
- 配置文件添加对应数据库配置
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/demospringboot?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&autoReconnect=true&maxReconnects=1&initialTimeout=50000&failOverReadOnly=false&zeroDateTimeBehavior=convertToNull&connectTimeout=50000&socketTimeout=50000
username: root
password: 123456
- mybatis
- 生成mapper,xml mapper.java(接口) entity后,执行mapper.xml文件的加载位置,xml会被mybatis自动加载,xml指明对应mapper.java的位置
- 使用时直接注入对应的接口
- yml 文件写入
# mybatid
mybatis:
mapperLocations: classpath:mapper/*.xml
日志集成
基础
- spring boot 默认日志系统为 logback
- 引入 spring-boot-starter-logging 依赖,一般在spring-boot-starter中已经导入;完整的依赖为
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
<version>2.2.4.RELEASE</version>
<scope>compile</scope>
</dependency>
使用
- 配置默认日志级别
- logging: level: root: debug ;root 属性必须要添加 。此方式指定默认所有的日志级别
- root 可以改为包名,用来配置指定包下的日志级别;(可以使用项目的最顶级的包名,一般不会重复)
- 配置日志输出位置
- 默认存在控制台输出
- 文件方式:
- logging.file.name: log/debug.log ,指定日志输出的文件位置;目录+文件名;使用相对路径方式时,其相对于项目本身,而非src;当仅指定文件名时,会生成于src 同级别的日志文件;
- logging.file.path 指定目录,会在该目录下生成spring.log 文件;
- 日志输出
- 使用sel4j 时,日志的占位符为“{}”;在输出前其会判断级别,如未达到输出级别,则不会进行日志内容的拼接
测试集成
- 导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
- 创建测试类
- 添加注释
@RunWith(SpringRunner.class) @SpringBootTest(classes={Application.class})
- Application 指项目启动类
- 添加注释
Redis集成
- 引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
- 配置pom文件
spring:
redis:
database: 0
host: 39.97.101.82
port: 6379
timeout: 1000
- 在类中注入RedisTemplate即可
@Autowired
RedisTemplate<String, String> redisTemplate;