第六章:SpringBoot配置(配置文件占位符)

总目录:SpringBoot学习教程


(一):在SpringBoot的配置文件中,我们可以使用SpringBoot提供的的一些随机数

${random.value}、${random.int}、${random.long}
${random.int(10)}、${random.int[1024,65536]}

还可以使用我们这个配置文件中自己在前面定义的值,例如:

person.last-name=张三
person.dog.name=${person.last-name}小狗

还有,我们如果前面没有这个值呢?

我们可以使用${app.name:金毛}来指定找不到属性时的默认值。


我们来用代码测试一下:

实体类:

package com.example.springboot02.bean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "person")
public class Person3 {

    private String lastName;
    private Integer age;
    private Integer tizhong;

}
//这里省略了get set toString方法了 ,用的时候自行补全,我为了这里展示的时候美观

我们在配置文件中定义值:

#自定义值
person.last-name=王五
#使用springboot 自带的值
person.age=${random.int}
#找不到属性时的默认值
person.tizhong=${person.tz:10}

测试:在项目的test目录下

package com.example.springboot02;

@RunWith(SpringRunner.class)
@SpringBootTest
public class Springboot02ApplicationTests {
	@Autowired
	Person3 person3;
	@Test
	public void contextLoads() {
		System.out.println(person3);
	}
}

结果就是我们再配置文件中设置的值:

第六章:SpringBoot配置(配置文件占位符)_第1张图片

下一节:第七章:SpringBoot配置——(Profile不同环境配置)

你可能感兴趣的:(Springboot,yml)