SpringBoot专题学习Part7:注解方式@PropertySource和@ImportResource导入配置文件

@PropertySource注解

@PropertySource加载指定的配置文件

@ConfigurationProperties默认是从全局配置文件中获取值
若不是从全局配置文件中获取值 则须加上@PropertySource注解来指定

@PropertySource的value值还可以传入数组的方式加载多个配置文件

person.name=陈涛
person.age=19
person.isStudent=true
person.birth=2020/01/01
person.maps.k1=v111
person.maps.k2=v211
person.lists=pico,tankman
person.dog.name=dog
person.dog.age=2

用@PropertySource注解指定配置文件:

@Component
@PropertySource(value = {"classpath:person.properties"})
@ConfigurationProperties(prefix = "person")
public class Person {
    private String name;
    private Integer age;
    private Boolean isStudent;
    private Date birth;
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;

    ...
}
@Autowired
private Person person;

@Test
void contextLoads() {
    System.out.println(person);
}

在这里插入图片描述测试成功

@ImportResource注解

@ImportResource:导入Spring的配置文件 让配置文件中的内容生效

SpringBoot中没有Spring的配置文件 且自己编写的配置文件也不能够被自动识别
若想让Spring的配置文件生效 加载进ioc容器 则需要将@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="net.zjitc.springboot.service.HelloService"/>
</beans>

开始测试:

@Autowired
ApplicationContext ioc;

@Test
public void testHelloService()
{
    System.out.println(ioc.containsBean("helloService"));
}

结果:false
在这里插入图片描述
添加@ImportResource注解并指定Spring配置文件的路径:

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

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

}

结果:true
在这里插入图片描述


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值