springboot配置文件yml使用

梦里梦外; 2022-05-13 19:28 1189阅读 0赞

SpringBoot项目属性配置

如果使用IDEA创建Springboot项目,默认会在resource目录下创建application.properties文件,在SpringBoot项目中,也可以使用yml类型的配置文件代替properties文件,下面我们具体介绍:

1.应用配置文件(.properties或.yml):

1.在resource目录下创建application.properties文件,并添加一些配置:

  1. server.port=8081
  2. server.context-path=/girl

2.在resource目录下创建application.yml文件,并添加一些配置:

  1. #注意:在yml文件中添加value值时,value前面需要加一个空格
  2. server:
  3. port: 8081
  4. context-path: /girl #使用localhost:8081/girl/hello
  5. cupSize :B

2.单个的获取配置文件中的内容:

在字段上使用@Value("${配置文件中的key}")的方式获取单个的内容

1.在resource目录下创建application.yml文件,并添加一些配置,在yml文件中,key:后面需要添加一个空格,然后是value值,假设配置如下:

  1. #注意:在yml文件中添加value值时,value前面需要加一个空格
  2. ip: 127.0.0.0
  3. port: 8080

2.创建一个ConfigController类,获取配置文件中的内容并赋值给相应的字段:

  1. @RestController
  2. public class ConfigController {
  3. @Value("${ip}")//获取application.yml文件中名为ip的value值
  4. private String ip;
  5. @Value("${port}")//获取application.yml文件中名为port的value值,并且自动完成数据类型转换
  6. private Integer port;
  7. @RequestMapping("/config")
  8. public String config() {
  9. return "ip:"+ip+",port:"+port;
  10. }
  11. }

3.在浏览器中输入http://localhost:8080/config,可以看到输出了配置文件中配置的内容:

20170408183627839

4.当然也可以在配置里面使用当前配置,如下:

  1. ip: 127.0.0.0
  2. port: 8080
  3. content: "ip:${ip},port:${port}"
  4. @Value("${content}")
  5. private String content;

3.使用Bean自动注入获取配置文件中的内容:

假如配置文件中有很多内容,一个一个获取将会很麻烦,那么我们另外一种方式去获取配置文件中的信息

1.在配置文件中添加以下信息(注意格式),此处我们使用了一个名为devconfig的前缀:

  1. devconfig:
  2. ip: 127.0.0.0
  3. port: 8080

2.创建ConfigBean,在类中添加@Componet和@ConfigurationProperties注解,其prefix设置为devconfig,将获取yml中前缀为devconfig下的配置信息:

  1. @Component
  2. @ConfigurationProperties(prefix = "devconfig")//获取前缀为devconfig下的配置信息
  3. public class ConfigBean {
  4. private String ip;//名字与配置文件中一致
  5. private Integer port;
  6. public String getIp() {
  7. return ip;
  8. }
  9. public void setIp(String ip) {
  10. this.ip = ip;
  11. }
  12. public Integer getPort() {
  13. return port;
  14. }
  15. public void setPort(Integer port) {
  16. this.port = port;
  17. }
  18. }

3.在ConfigController中使用@Autowrite对bean自动注入,实例化bean:

  1. @RestController
  2. public class ConfigController {
  3. //自动注入,实例化bean
  4. @Autowired
  5. private ConfigBean configBean;
  6. @RequestMapping("/config")
  7. public String config() {
  8. return "另一种方式: ip:"+configBean.getIp()+",port:"+configBean.getPort();
  9. }
  10. }

4.多个配置文件切换的使用:

1.假设开发环境使用ip为:127.0.0.0,使用端口为:8080,生产环境使用ip为:127.0.0.1,使用端口为:8081

下面来修改配置文件,在resource目录下创建application-produce.yml和生产环境配置文件application-dev.yml:

  1. config:
  2. ip: 127.0.0.0
  3. port: 8080
  4. config:
  5. ip: 127.0.0.1
  6. port: 8081

application.yml中配置生效的配置文件,此处设为produce,也就是使用application-produce.yml文件:

  1. spring:
  2. profiles:
  3. active: produce

2.也可通过启动jar包时添加参数来更改生效的配置文件,命令为:java -jar XXX.jar –spring.profiles.active=poduce(这样就可以多环境下同时使用了)

发表评论

表情:
评论列表 (有 0 条评论,1189人围观)

还没有评论,来说两句吧...

相关阅读