继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

004SpringBoot之@PropertySource与@ImportResource的区别

RISEBY
关注TA
已关注
手记 309
粉丝 70
获赞 317

一、@PropertySource

1、定义

自定义配置文件名称,多用于配置文件与实体属性映射。

2、使用

上一章节我们介绍了如何从配置文件里获取值,与JavaBean做映射。但是存在的问题是我们是从主配置(application.yml)里读取的。如果全部的配置都写到application里,那就乱套了。所以我们可以按照不同模块自定义不同的配置文件。

2.1、配置

person.properties

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

2.2、JavaBean

@PropertySource(value = {"classpath:person.properties"})@ConfigurationProperties(prefix = "person")@Componentpublic 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

1、定义

将外部的配置文件加载到程序中来,比如我们定义一个beans.xml文件,里面配置了一个bean,默认情况下这个bean是不会加载到Spring容器中来的。我们需要@ImportResource注解将这个配置文件加载进来。

2、使用

2.1、配置

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

2.2、JavaBean

public class HelloService {}

2.3、测试类

@RunWith(SpringRunner.class)@SpringBootTestpublic class Springboot02ConfigApplicationTests {    @Autowired
    private ApplicationContext ioc;    @Test
    public void testHelloService() {        boolean helloService = ioc.containsBean("helloService");
        System.out.println(helloService);
    }
}

2.4、测试结果

false

2.5、修改运行类

@SpringBootApplication@ImportResource(locations = {"classpath:beans.xml"})public class Springboot02ConfigApplication {    public static void main(String[] args) {
        SpringApplication.run(Springboot02ConfigApplication.class, args);
    }
}

2.6、测试结果

true

PS:因为我们将外部的配置文件引入了,@ImportResource(locations = {"classpath:beans.xml"})

2.7、注意

@ImportResource这么看的话没卵用,因为我们现在都没了配置文件了,所以引入什么呢?其实并不然,比如:dubbo还是需要靠配置文件来配置bean的,这时候就需要此注解了。(我知道dubbo也可以按照注解来配置,我只是举个例子。),若只为了注入一个bean,完全可以采取Spring的@Bean注解。



作者:编程界的小学生
链接:https://www.jianshu.com/p/ec628153b7a2

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP