1、@ConfigurationProperties支持松散绑定,@Value不支持,属性名必须一致;松散绑定是配置文件中的属性书写方式,lastName和last-name就是同一个,这种写法就是松散绑定的写法。
@ConfigurationProperties支持JSR30数据校验,@Value不支持;JSR30数据校验就是校验器配置,文件注入值数据校验,只能使用ConfigurationProperties。
@Component
@Validated
public class Person {
@Email
@Value("${person.last-name}")
private String lastName;
private Integer age;
private Boolean boss;
private Date birth;
private Map<String, Object> maps;
private List<Object> lists;
private Dog dog;
......生成toString()和Getter and Setter方法
application.properties:
person.last-name=李四
person.age=12
person.birth=2017/12/15
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=dog
person.dog.age=15
测试:
@RunWith(SpringRunner.class)
@SpringBootTest
class SpringBoot02ConfigApplicationTests {
@Autowired
Person person;
@Test
public void contextLoads() {
System.out.println(person);
}
}
2、@ConfigurationProperties:默认加载全局的配置文件。@ImportResources:导入Spring的配置文件,让配置文件里面的内容生效。
一个xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="helloService" class="com.fu.springboot.service.HelloService"></bean>
</beans>
测试:
@RunWith(SpringRunner.class)
@SpringBootTest
class SpringBoot02ConfigApplicationTests {
@Autowired
Person person;
@Autowired
ApplicationContext applicationContext;
@Test
public void testHelloService() {
Object o = applicationContext.getBean("helloService");
System.out.println(o);
}
@Test
public void contextLoads() {
System.out.println(person);
}
}
@ImportResource标注在主配置类上,在参数locations中写上配置文件路径就能导入Spring的配置文件即可生效。
3、RandomValuePropertySource:配置文件中可以使用随机数。占位符获取之前配置的值,如果没有可以使用:指定默认值。
person.age=12${random.int}
person.dog.name=${person.last-name}_dog
1426

被折叠的 条评论
为什么被折叠?



