springboot 读取配置文件
一.读取springboot 自带的application.properties或application.yml文件
1.通过@Value注解来读取
application.properties文件内容:
name=1
user.name=2
读取方式:
@Value("${name}")
private String name;
@Value("${user.name}")
private String userName;
如果要设置默认值:
@Value("${name:张三}")
private String name;
//设置默认值为空置
@Value("${user.name:#{null}}")
private String userName;
2.通过@ConfigurationProperties(prefix="***")来读取
@Data @Component @ConfigurationProperties(prefix="user") public class TestBean{ String name; }
二.读取springboot中自定义的properties文件,例如test.properties
1.通过@Value和@PropertySource结合取值
@Component @PropertySource("classpath:test.properties") public class TestBean{ @Value("${name}") private String name; @Value("${user.name}") private String userName; }
2.通过@ConfigurationProperties和@PropertySource结合取值
@Component @ConfigurationProperties(prefix="user") @PropertySource("classpath:test.properties") public class TestBean{ String name; }
故乡明

浙公网安备 33010602011771号