第一种 属性读取
第二种 类读取。
第三种 读取List方式:
第四种 读取List<对象>:
出现下面的问题:
可以忽略,如果你觉的看着不舒服,可以点击进去复制他的依赖 添加到 pom 里面就好。
属性读取。
1、在application.properties 中添加 要读取的配置:
hello = hello world
2、属性上 添加 (@Value("${hello}"))
@RestController
public class UserController{
@Value("${hello}") //如果是 多级,可以用 '.' 来连接("${xxx.xxx.xxx}")
private String helloText;
@RequestMapping("/hello")
public String hello(){
return helloText;
}
}
类读取。
1、在src/main/resource。创建custom.properties文件:
user.name=zll
user.age=32
user.score=98.5
2、创建读取类
@Component
@PropertySource(value = "classpath:custom.properties",encoding = "utf-8")
@ConfigurationProperties("user")
@Data
public class UserDto {
private String name;
private int age;
private double score;
}
读取List方式:
custom.properties
country.city[0]=bj
country.city[1]=上海
country.city[2]=shengZheng
country.city[3]=温江
读取方式
@Component
@PropertySource(value = "classpath:custom.properties",encoding = "utf-8")
@ConfigurationProperties("country")
@Data
public class CountryDto {
private List<String> city;
}
读取静态对象方式:
需要给静态属性设置 set方法:
@Component
public class BaseConfig {
public static String BASE_URL;
@Value("${server.servlet.context-path}")
public void setBaseUrl2(String path) {
BASE_URL = path;
}
}
读取List<对象>:
custom.properties 中
group.user[0].name=张三
group.user[0].age=18
group.user[1].name=李四
group.user[1].age=19
group.user[1].score=99
group.user[2].name=王五
group.user[2].score=82.2
读取方式:
@Component
@PropertySource(value = "classpath:custom.properties",encoding = "utf-8")
@ConfigurationProperties("group") //这里 必须填写 属性的开始名称 group.user[0].name=张三
@Data
public class UserListDto {
// 属性名必须和 自定义 温江里面的 名字一样 group.user[0].name=张三
List<User> user;
}