在 java 项目中,application.yml 文件常用于配置各种应用程序属性,尤其是在使用 spring boot 框架时。
1.1 基本配置
server:
port: 8080 # 设置应用的端口号
spring:
application:
name: my-app # 设置应用的名称,一般与项目名称一致1.2 配置数据源
假设你要配置一个 mysql 数据源,常用的配置如下:
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydatabase?usessl=false&servertimezone=utc # 数据库url
username: root # 数据库用户名
password: mypassword # 数据库密码
driver-class-name: com.mysql.cj.jdbc.driver # jdbc驱动类名1.3 配置连接池
配置数据库 hikaricp 连接池(spring boot 默认的连接池):
spring:
datasource:
hikari:
maximum-pool-size: 10 # 最大连接池大小
minimum-idle: 5 # 最小空闲连接数
idle-timeout: 30000 # 连接空闲时间(毫秒)
connection-timeout: 20000 # 连接超时时间(毫秒)
max-lifetime: 1800000 # 连接最大生命周期(毫秒)1.4 mybatis 配置
mybatis 是一个优秀的持久层框架,支持定制化 sql、存储过程以及高级映射。
配置:mapper-locations: classpath:mapper/*.xml
就可以把xml文件放在 resource/mapper包下
配置:type-aliases-package: com.example.demo.model
问题:可以看到resulttype每次都要配置好长的全类名。
<select id="getuser" resulttype="com.wiener.study.pojo.user" parametertype="int"> </select>
项目启动的时候,mybatis会自动扫描指定包及其子包下的所有实体类并将别名装配到上下文中,默认别名是类名和类名首字母小写。
例如,项目包含多个模块,每个模块(例如 study)都有自己的pojo,扫描多个包可以只写到模块的父级目录:
mybatis:
type-aliases-package: com.wiener.demo # 具体到模块study所在的父级目录类user为com.wiener.study.pojo包下的实体类,这里使用别名user即可。在上述配置的基础上,还可以通过在实体类上加入@alias注解来进一步设置别名:
// 自定义实体类别名
@alias("usermsg")
public class user implements serializable {
//实现serializable接口
private static final long serialversionuid = -2241172936329900646l;
private string id;
private string password;
private string name;
}此时,user类的别名被重定义为usermsg,select语句更新如下:
<select id="getuser" resulttype="usermsg" parametertype="int"> </select>
mybatis:
mapper-locations: classpath:mapper/*.xml # mapper xml 文件的位置
type-aliases-package: com.example.demo.model # 别名包路径
configuration:
map-underscore-to-camel-case: true # 开启驼峰命名自动映射
log-impl: org.apache.ibatis.logging.stdout.stdoutimpl # 开启sql日志1.5 mybatis-plus 配置
mybatis-plus 是 mybatis 的增强工具,提供了更多的功能,如 crud 操作、分页、sql 注入器等。
mybatis-plus:
mapper-locations: "classpath*:/mapper/**/*.xml" # mapper.xml文件地址,当前这个是默认值。
type-aliases-package: com.example.demo.model # 别名包路径
global-config:
db-config:
logic-delete-field: deleted # 逻辑删除字段名称
logic-delete-value: 1 # 逻辑删除值
logic-not-delete-value: 0 # 逻辑未删除值
configuration:
map-underscore-to-camel-case: true # 开启驼峰命名自动映射1.6 redis 配置
redis 是一个高性能的 key-value 存储系统,常用于缓存、消息队列等场景。
spring:
redis:
host: localhost # redis 服务器地址
port: 6379 # redis 服务器端口
password: mypassword # redis 密码
database: 0 # 使用的数据库索引
timeout: 2000 # 连接超时时间(毫秒)
lettuce:
pool:
max-active: 8 # 连接池最大连接数
max-wait: -1 # 连接池最大阻塞等待时间(负数表示不限制)
max-idle: 8 # 连接池中的最大空闲连接
min-idle: 0 # 连接池中的最小空闲连接总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论