前言
在开发中,我们可以通过自定义配置来灵活配置我们的项目。过去,在 SpringMVC 中,我们需要在各种 XML 中定义我们的各项配置,使用起来相对繁琐。而 SpringBoot 为我们提供了更为方便的方式定义配置,只需要在 application.yml
中添加我们需要的配置,然后通过注解读取配置即可。
使用 @Value
读取配置
在类中,我们可以通过给属性打上 @Value
注解,将配置中的参数值绑定到属性上。
在 application.yml
中,我们添加如下配置。
myconfig:
name: InterHorse
创建测试用的 Controller 类,将绑定的参数值打印到日志中。
@Controller
public class MyController {
private static final Logger LOG = LoggerFactory.getLogger(MyController.class);
@Value("${myconfig.name}")
private String name;
@ResponseBody
@RequestMapping(value = "/test1")
private void test1() {
LOG.info("name:{}", name);
}
}
在 @Value
中,使用 ${}
读取配置中的内容。Yml 中每一层级用"."号分割。
调用 http://127.0.0.1:8080/test1 接口,配置的 name 属性值 InterHorse 即被输出。
c.i.s.c.controller.MyController : name:InterHorse
使用 @ConfigurationProperties
读取配置
除了使用 @Value
直接将配置绑定到属性上,我们也可以使用 @ConfigurationProperties
注解,将配置绑定到实体中。
在 application.yml
中,继续添加如下配置。
myconfig:
name: InterHorse
city: Beijing
friends:
- Martin
- Bill
- Jenny
age: 3
其中,friends 下的 “-” 表示为数组类型。
创建 MyConfigProp 实体类
@Component
@ConfigurationProperties(prefix = "myconfig")
public class MyConfigProp {
private String name;
private String city;
private List<String> friends;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public List<String> getFriends() {
return friends;
}
public void setFriends(List<String> friends) {
this.friends = friends;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
@ConfigurationProperties
中的 prefix 为 yml 中想要读取的配置的层级关系。类中的属性名和要和自定义配置中的属性名相匹配,SpringBoot 会根据宽松的绑定规则将配置与实体中的属性绑定。
有关宽松的绑定规则,如下面示例所示,所有格式都会被识别为 myName 属性:
config.my-name = InterHorse
config.myName = InterHorse
config.myname = InterHorse
config.my_name = InterHorse
config.MY_NAME = InterHorse
注意,@Component
的作用是为了让 SpringBoot 将该实体扫描到,这样 @ConfigurationProperties
注解才会生效。
接下来我们进行还是创建一个接口测试,在上面的 Controller 中填下如下内容
@Controller
public class MyController {
private static final Logger LOG = LoggerFactory.getLogger(MyController.class);
@Autowired
private MyConfigProp myConfigProp;
@ResponseBody
@RequestMapping(value = "/test2")
private void test2() {
List<String> friends = myConfigProp.getFriends();
LOG.info("name:{}, city:{}, age:{}",
myConfigProp.getName(), myConfigProp.getCity(), myConfigProp.getAge());
for (String n : friends) {
LOG.info("friend name:{}", n);
}
}
}
调用 http://127.0.0.1:8080/test2 接口,配置即被输出。
c.i.s.c.controller.MyController : name:InterHorse, city:Beijing, age:3
c.i.s.c.controller.MyController : friend name:Martin
c.i.s.c.controller.MyController : friend name:Bill
c.i.s.c.controller.MyController : friend name:Jenny
以上就是 SpringBoot 中自定义配置的读取方法。
本章代码地址:GitHub
我是因特马,一个爱分享的斜杠程序员~
欢迎关注我的公众号:一只因特马
原文作者: 一只因特马
原文链接: https://www.interhorse.cn/a/4223378434/
版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-ND 许可协议。转载请注明出处!