学习的点点滴滴

Email : 107311278@qq.com
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Spring Boot @PropertySource与@ImportResource的区别

Posted on 2019-09-26 17:47  v薛定谔的猫v  阅读(486)  评论(0)    收藏  举报

@PropertySource 自定义配置文件名称,多用于配置文件与实体属性映射。
引入说明
在从配置文件里获取值,与JavaBean做映射。存在一个问题,我们是从主配置(application.yml)里读取的。如果全部的配置都写到application里,那么主配置就会显得特别臃肿。为了按照不同模块自定义不同的配置文件引入了@PropertySource

配置

person.properties
person.lastName=李四
person.age=25
person.birth=2017/12/15
person.boss=true
person.maps.key1=value1
person.maps.key2=value2
person.lists=a,b,c
person.dog.name=dog
person.dog.age=2

JavaBean

@PropertySource(value = {"classpath:person.properties"})
@ConfigurationProperties(prefix = "person")
@Component
public class Person {
    private String lastName;
    private Integer age;
    private boolean isBoss;
    private Date birth;

    private Map<String, Object> maps;
    private List<Object> lists;
    private Dog dog;
    ...setter/getter/toString...
}

这样一个注解(@PropertySource(value = {“classpath:person.properties”}))就可以搞定不在主配置里读取,按照不同的功能模块划分出不同的配置文件。

@ImportResource
一般情况下我们自定义的xml配置文件,默认情况下这个bean是不会加载到Spring容器中来的。需要@ImportResource注解将这个配置文件加载进来。

配置

<?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.chentongwei.springboot.service.HelloService"></bean>
</beans>

JavaBean

public class HelloService {

}

 

修改启动类

@SpringBootApplication
@ImportResource(locations = {"classpath:beans.xml"})
public class Springboot02ConfigApplication {

    public static void main(String[] args) {
        SpringApplication.run(Springboot02ConfigApplication.class, args);
    }
}

@PropertySource 用于引入*.Properties或者 .yml 用于给javabean注入值
@ImportResource 用于引入.xml 类型的配置文件 在spring boot中已经被配置类替代
@PropertySource 一般用在javabean的类名上
@ImportResource一般用于启动类上