1、随机数
在Spring Boot 配置文件中我们可以使用后随机数random,语法如下:
${random.value}、${random.int}、${random.long}
${random.int(10)}、${random.int[1024,65536]}
下面通过例子进行学习:
- 创建于一个cat类
package cn.zhangyu.bean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "cat")
public class Cat {
private String name;
private int age;
@Override
public String toString() {
return "Cat{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
- application.properties
cat.name=${random.value}
cat.age=${random.int}
- 测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class Springboot1ApplicationTests {
@Autowired
private Cat cat;
@Test
public void test(){
System.out.println(cat);
}
}
结果:Cat{name='eab61b74218a98f8af2526c83c9e0a08', age=-723867268}
2、占位符获取之前配置的值
我们再给猫加几个属性,看看如何使用占位符
- application.properties
cat.name=小顾
cat.age=5
cat.nickName=${cat.name}
cat.birthday=${random.int}
- Cat
package cn.zhangyu.bean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "cat")
public class Cat {
private String name;
private int age;
private String nickName;
private String birthday;
@Override
public String toString() {
return "Cat{" +
"name='" + name + '\'' +
", age=" + age +
", nickName='" + nickName + '\'' +
", birthday=" + birthday +
'}';
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
结果: Cat{name='小顾', age=5, nickName='小顾', birthday=1313024468} 可以看到占位符有效
但是这并不是最佳实践,我们继续看看下面这种情况
cat.name=小顾
cat.age=5
cat.nickName=${cat.hello}
cat.birthday=${random.int}
如果在配置文件中出现一个没有过的属性,会是什么结果呢?
我们看看输出结果Cat{name='小顾', age=5, nickName='${cat.hello}', birthday=981210833}
不会报错,直接输出了cat.hello。 有些情况下可能我们会学错是很正常的,那么我们可以加一个默认值。这是最好的写法。
cat.name=小顾
cat.age=5
cat.nickName=${cat.hello:hello }cat
cat.birthday=${random.int}
结果:Cat{name='小顾', age=5, nickName='hello cat', birthday=1820983133}
如果在没有值的情况下,我们可以指定默认值, :默认值
。