my:
name: boot
age: 12
@RestController
public class ConfigController {
@Value("${my.name}")
private String name;
@Value("${my.age}")
private int age;
@RequestMapping(value = "/config")
public String config(){
return name+":"+age;
}
}
my:
name: boot
age: 20
# ${random} ,用来生成各种不同类型的随机值。
number: ${random.int}
uuid: ${random.uuid}
max: ${random.int(10)}
value: ${random.value}
greeting: hi,i'm ${my.name}
@ConfigurationProperties(prefix = "my")
public class ConfigBean {
private String name;
private int age;
private int number;
private String uuid;
private int max;
private String value;
private String greeting;
get...set...省略
使用idea自动生成get,set和toString
}
@EnableConfigurationProperties({ ConfigBean.class })
@RestController
public class ConfigBeanController {
@Autowired
private ConfigBean configBean;
@RequestMapping("/configbean")
public String config(){
// 输出所有字段的值
return configBean.toString();
}
}
com.boot.name=boot
com.boot.age=20
@Configuration
@PropertySource(value = "classpath:test.properties")
@ConfigurationProperties(prefix = "com.boot")
public class TestBean {
private String name;
private int age;
省略get,set,tostring
}
@EnableConfigurationProperties({TestBean.class})
@RestController
public class TestBeanController {
@Autowired
private TestBean testBean;
@RequestMapping("/testconfig")
public String testConfig() {
return testBean.toString();
}
}
spring:
profiles:
active: dev
my:
name: dev
age: 11
#server:
# port: 8082
ConfigBean{name='dev', age=11, number=-1422131996, uuid='5bebc511-f1a4-4f2b-95ed-540e4b48e8bd', max=0, value='8b96a5bbde492fb189e4fa52573c9caf', greeting='hi,i'm dev'}
原文:https://www.cnblogs.com/wang7/p/10776334.html