package com.learn.bean;import java.util.Date;
import java.util.List;
import java.util.Map;import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;/*** 将配置文件中配置的每一个属性的值,映射到这个组件* @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中的相关的配置进行绑定* prefix="person":配置文件中哪个下面的所有属性进行映射* * 只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能;* 默认从全局配置文件中获取值;*/
//@PropertySource(value= {"classpath:person.properties"})
@Component
@ConfigurationProperties(prefix="person")
//@Validated
public class Person {/*** * * */// lastName必须是邮箱格式//@Email
// @Value("${person.last-name}")private String lastName;
// @Value("#{10*2}")private Integer age;@Value("true")private Boolean boss;private Date birth;
// @Value("${person.maps}")private Map maps;private List
package com.learn.springboot;import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;import com.learn.bean.Person;/*** SpringBoot单元测试** 可以在测试期间很方便的类似编码一样进行自动注入等容器的功能*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBoot02ConfigurationTests {@AutowiredPerson person;@AutowiredApplicationContext ioc;@Testpublic void testHelloService() {boolean b = ioc.containsBean("helloService02");System.out.println(b);}@Testpublic void contextLoads() {System.out.println(person);}}
我现在前面没有配人名,他现在就解析出错,出错的原因呢,是我们要绑定person的值,我们要绑定person里面的每一个属性,他都要在配置文件中要找到,然后我们不能够解析person.last-name,我们配置文件中没有lastName相关的信息,我们写一个person.hello,我们从来没有写过person.hello的值,如果获取不到值就是默认的表达式,但是我们可以使用一个冒号,给定一个默认值,如果person.hello取不出值,我们就默认使用后面这一串,dog就叫hello_dog没问题
#server.port=8081person.last-name=\u674E\u56DB${random.uuid}
person.age=${random.int}
person.birth=2017/12/15
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=${person.hello:hello}_dog
person.dog.age=15
这就是我们的配置文件占位符,随机数的其他用法,大家在这试一试就行了,我们可以用这几个随机数,第一个我们能够用这些随机数

占位符获取之前配置的值,如果没有,可以使用指定默认值,这些随机数也能用,包括我们获取默认值也能用

本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!