SpringBoot总结

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值