明确学习目标
1、 application.properties配置文件
2、 application.yaml配置文件
3、 使用注解@ConfigurationProperties和@Value注入属性,两种注解对比分析
5、 使用@Configuration编写自定义配置类
6、 使用Profile文件进行多环境配置
7、 使用@Profile注解进行多环境配置
(一)application.properties配置 @ConfigurationProperties注解
- application.properties配置person相关信息
##??????Person??????(拷贝后将以下注释去掉)
#person.id=1
#person.name=tom
#person.hobby=play,read,sleep
#person.family=father,mother
#person.map.k1=v1
#person.map.k2=v2
#person.pet.type=dog
#person.pet.name=kity
- 新建person类并用@ConfigurationProperties(prefix = "person")注入
@Component // 用于将Person类作为Bean注入到Spring容器中
@ConfigurationProperties(prefix = "person") // 将配置文件中以person开头的属性注入到该类中,
// 用来初始化对象(假如没有数据库,对象值需要经常修改的情况)
@Data //get set 实现
@Validated //引入数据校验规则
public class Person {
// private int id; //id 去掉一个也可以正常显示,表明有些属性不配置也可以
//spel表达式
// @Value("#{5*2")
// private int id;
@Value("addStr") //用 @Value 注入并赋值
private String myAddStr ; //配置文件不存在该字段的情况
private String firstname ; //支持松散绑定
@Email
private String email ; //支持jsr303数据校验
private String name; //名称 去掉getname 则获取不到
private List hobby; //爱好
private String[] family; //家庭成员
private Map map;
private Pet pet; //宠物
get set 方法略。。。。
@Override
public String toString() {
return "Person{" +
// "id=" + id +
", myaddstr='" + myAddStr +
", name='" + name + '\'' +
", hobby=" + hobby +
", family=" + Arrays.toString(family) +
", map=" + map +
", pet=" + pet +
", firstname=" + firstname +
", email=" + email +
'}';
}
}
public class Pet {
private String type;
private String name;
}
- 测试
@Autowired
private Person person;
//@Autowired 与@Resource的区别
@Test
void contextLoads() {
//@ConfigurationProperties 测试
System.out.println(person);
}
(二)application.yml配置
配置person相关信息
person:
id: 2
name: 张三
first_name: 张 #松散配置 firstname 也可以
email: 3333@qq.com
hobby: [sing,read,sleep]
family: [father,mother]
map: {k1: v1,k2: v2}
pet: {type: cat, name: tom}
将(一)中第一点配置注释掉,再执行第三步的测试
(三)@Value注入以及与@ConfigurationProperties注入的区别
- 引入数据校验依赖
<!-- 数据校验-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
- 对比
参见0416项目,分析person、Student类

Student类:
@Component // 用于将Student类作为Bean注入到Spring容器中
public class Student {
// int num = 3 ;
// @Value("#{num}")
@Value("#{5*2}")
// @Value("${person.id}")
private int id; //id @Value 还支持SpEL 如 @Value("#{5*2}")
@Value("${person.name}") //获取配置name值
// @Value("${person.name}")
private String studentName; //名称
private List hobby; //爱好
private String[] family; //家庭成员
private Map map;
// @Value("${person.pet}")
private Pet pet; //宠物
@Override
public String toString() {
return "Student{" +
"id=" + id +
", studentName='" + studentName + '\'' +
", hobby=" + hobby +
", family=" + Arrays.toString(family) +
", map=" + map +
", pet=" + pet +
'}';
}
}
测试
@Resource
private Student student ;
@Test
void studentTest(){
//@Value 测试
System.out.println(student);
}
(四)自定义配置
- 创建自定义文件 test.properties,并写上
test.id=110
test.name=test
- 创建自定义配置类
在domain创建MyProperties类
@Configuration // 自定义配置类
@EnableConfigurationProperties(MyProperties.class) // 开启对应配置类的属性注入功能
@PropertySource("classpath:test.properties") // 指定自定义配置文件位置和名称
@ConfigurationProperties(prefix = "test") // 指定配置文件注入属性前缀
public class MyProperties {
private int id;
private String name;
....
- 测试
@Autowired
private MyProperties myProperties;
@Test
public void myPropertiesTest() {
//自定义配置测试
System.out.println(myProperties);
}
设想:
test.yml是否成功?是可以的。
(五)加载XML配置文件
- 在config包下新建MyService类。类中什么方法均不需要写
- resource下新增bean.xml文件(注意红色部分路径与你项目一致)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="myService" class="com.example.train0416.config.MyService" />
</beans>
- 在项目启动类添加注解 @ImportResource("classpath:beans.xml") // 加载自定义XML配置文件位置
- 测试
@Autowired
private ApplicationContext applicationContext;
@Test
public void iocTest() {
//编写自定义配置类,也就是定义在bean.xml中的类
//@ImportResource("classpath:beans.xml") // 加载自定义XML配置文件位置 在启动类添加
System.out.println(applicationContext.containsBean("myService"));
}
(六)自定义配置类
- 在config下新增 MyConfig类
@Configuration
public class MyConfig {
@Bean
public void myconfigMethod (){
System.out.println("我是自定义配置类,程序运行会被自动加载");
}
}
- 测试
不需要编写测试方法,启动项目则自动调用。说明自定义配置类是自动注入容器并执行。
(六)多环境配置(简单)
- 分别建立各个环境的配置文件
application-dev.properties //开发
server.port=8081 (各环境仅端口不一致)
application-test.properties //测试
application-prod.properties //生产
- 在公共配置文件添加(application.proerties/yml)(properties/yml文件)
# ??????profile???????
spring.profiles.active=prod
- 测试
启动项目查看运行的端口。
(七)多环境配置(@Profile)
- 新建DBConnector接口
public interface DBConnector {
public void configure();
}
- 新建DevDBConnector类,并继承 DBConnector接口
@Configuration
@Profile("dev") // 指定多环境配置类标识
public class DevDBConnector implements DBConnector {
@Override
public void configure() {
System.out.println("数据库配置环境dev");
}
}
- 新建PropDBConnector类,并继承 DBConnector接口
@Configuration
@Profile("prod") // 指定多环境配置类标识
public class ProdDBConnector implements DBConnector {
@Override
public void configure() {
System.out.println("数据库配置环境prod");
}
}
- 测试
新增DBController类
@RestController
public class DBController {
@Autowired
private DBConnector dbConnector;
@GetMapping("/showDB")
public String showDB(){
// http://localhost:8083/showDB
System.out.println("设置激活环境测试");
dbConnector.configure();
return "设置激活环境测试";
}
}
(八)随机值设置以及引用
- 在yml设置
# ??????????????
tom.age=${random.int[10,20]}
tom.description=tom??????${tom.age} //引用
tom.name=${random.name}
tom.getname=tom??????${tom.name}
bignum: ${random.long}
uuid: ${random.uuid}
num: ${radom.int(10)} //小于10的随机数
num2: ${random.int(3,20)} //设置3~20之间的随机数
- 测试
@Value("${tom.description}")
private String description;
@Value("tom的姓名可能是${tom.name}")
private String getname ;
@Test
public void placeholderTest() {
//控制台打印乱码解决方法
// 方法一 打开 File --> settings --> Editor --> File Encodings 把编码都设置为 UTF-8 的形式
// 方法二 打开idea的 设置 界面,搜索 maven ,点击 Maven --> Runner --> VM Options ,填上-Dfile.encoding=GB2312
// 方法三 打开 Run --> Edit Configurations --> 选择文件 在 VM options 中加上 -Dfile.encoding=UTF-8
// 最后若以上都没有解决,则是开发工具和系统环境编码格式不匹配即为jdk版本过高,可以更换为上一版本的jdk
//随机值设置
System.out.println(description);
System.out.println(getname);
}
附件1:POM文件依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- @Data -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- 数据校验-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
本文详细介绍了SpringBoot中配置文件的应用,包括application.properties和application.yml的使用,@ConfigurationProperties和@Value注解的对比分析,自定义配置类的创建,多环境配置的实现,以及如何通过@Profile进行环境特定的配置。此外,还涉及了随机值设置和占位符引用的使用。

495

被折叠的 条评论
为什么被折叠?



