spring中读取配置文件的方式,以及配置文件如何写

application.properties

spring.application.name=spring-boot-simple-study
server.port=8080

application.yaml

server:
  port: 8082
name: yaml

#一、对象 map 键值对集合
# 行外写法
person:
  name: zhangsan
  age: 23
  address:
    - beijing
    - shanghai
    - guangzhou
    - shenzhen
# 行内写法
person2: {name: zhangsan2,age: 24}
#二、数组
# 行外写法
address:
  - beijing
  - shanghai
  - guangzhou
  - shenzhen
# 行内写法
address2: [beijing, shanghai, guangzhou, shenzhen]

#三、纯量
msg1: 'hello \n world !' #单引号忽略转义字符
msg2: "hello \n world !" #双引号识别转义字符


#四、参数引用
person3:
  name: {name} #会把前面定义的name=yaml赋值到这里

application.yml

server:
  port: 8081
name: yml

1 Config类读取配置文件: 

@Data
@Configuration
public class Config {
    @Value("${person.name}")
    private String name;
    @Value("${person.age}")
    private String age;
    @Value("${msg1}")
    private String msg1;
    @Value("${msg2}")
    private String msg2;
}

2 Person实体类+@ConfigurationProperties获取配置

@Data
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private String name;
    private String age;
    //private List<String> addr;
    private String[] address;
    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age='" + age + '\'' +
                ", addr=" + address +
                '}';
    }
}

3  Environment获取配置

@RestController
public class Control {
    /** 1、使用@Value注解获取配置 */
    @Autowired
    Config config;
    @GetMapping("/get1")
    public void viewMsg() {
        System.out.println(config.getMsg1());
        System.out.println(config.getMsg2());
    }
    @PostMapping("/viewPersonName")
    public void viewName(){
        System.out.println(config.getName());
    }
    /** 2、import org.springframework.core.env.Environment;  */
    @Autowired
    public Environment environment;
    @GetMapping("/get2")
    public void viewEnvironmentGetValue(){
        System.out.println(environment.getProperty("name")); // yaml
        System.out.println(environment.getProperty("address[0]")); // beijing
    }
    /** 3、/*/
    @Autowired
    Person person;
    @GetMapping("/get3")
    public void view_configurationPropertiesGetValue(){
        System.out.println(person.getName());
        System.out.println(person.getAge());
        for (String a : person.getAddress()) {
            System.out.println(a);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值