SpringBoot配置文件的占位符两种方式介绍与使用
占位符
配置文件的占位符,有两种:
- 1.随机数
${random.value},${random.int},${random.dog},${random.int(10)},${random.int[1023,65536]}
- 2.占位符获取之前配置的值,如果没有可以使用:指定默认值
占位符使用
第一种:随机数
person.last-name=zhangsan${random.uuid}
person.age=${random.int}
person.birth=2017/12/12
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,v
person.dog.name=${person.last-name}_dog
#person.dog.name=${person.hello:hello}_dog
person.dog.age=2
Person 类
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
/**
* <bean class="Person">
* <property name="lastNme" value="字面量/${key}从环境变量、配置文件中获取值/#{SpEl}">
*
* </property>>
* </bean>
*/
private String lastName;
private Integer age;
private Boolean boss;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Boolean getBoss() {
return boss;
}
public void setBoss(Boolean boss) {
this.boss = boss;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public Map<String, Object> getMaps() {
return maps;
}
public void setMaps(Map<String, Object> maps) {
this.maps = maps;
}
public List<Object> getLists() {
return lists;
}
public void setLists(List<Object> lists) {
this.lists = lists;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
@Override
public String toString() {
return "Person{" +
"lastName='" + lastName + '\'' +
", age=" + age +
", boss=" + boss +
", birth=" + birth +
", maps=" + maps +
", lists=" + lists +
", dog=" + dog +
'}';
}
}
Dog类
public class Dog {
// @Value("${person.dog.name}")
private String name;
// @Value("${person.dog.age}")
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
测试类:
@RunWith(SpringRunner.class)
@SpringBootTest
class QueueApplicationTests {
@Autowired
Person person;
// @Autowired
// ApplicationContext ioc;
// @Test
// public void testHelloService(){
// boolean flag = ioc.containsBean("helloService");
// System.out.println(flag);
// }
@Test
void contextLoads() {
System.out.println(person);
}
}
测试结果展示:
第二种:占位符获取之前配置的值,如果没有可以使用:指定默认值
没有person.hello这个属性,可以使用冒号:指定默认属性hello
person.last-name=zhangsan${random.uuid}
person.age=${random.int}
person.birth=2017/12/12
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,v
#person.dog.name=${person.last-name}_dog
person.dog.name=${person.hello:hello}_dog
person.dog.age=2
测试结果: