SpringBoot 注解@PropertiySource读取外部属性文件与注解@ImportResource引入自定义spring的xml配置文件和配置类

一、注解@PropertiySource读取外部属性文件

@ConfigurationProperties和@Value两个注解能从配置文件中获取数据,且只能从全局配置文件中获取,

如果有些配置数据需要他离出来,比如数据库连接信息放 jdbc.properties 里,可使用注解@PropertiySource读取外部属性文件。

 

1、在前面的springbootdemo1项目中 中定义 user.properties 外部属性文件

     application.yml 全局配置文件为空,  user.properties 外部属性文件定义User类信息

#user类
user.id=2001
user.username=李四
user.pazzword=lisi123
user.birthday=2019/05/08
user.list=aaa,bbb,ccc
user.map.key1=value1
user.map.key2=value2
user.address.id=2001
user.address.detail=浙江杭州

2、User 类 通过注解@PropertiySource读取 user.properties 外部属性文件

@Component
@PropertySource("classpath:user.properties")
public class User implements Serializable {
   ...属性信息没变
}

3、运行测试类即可读取到数据

  

 

二、注解@ImportResource引入自定义spring的xml配置文件和配置类

1、注解@ImportResource引入自定义spring的配置xml文件(不推荐
Spring的配置文件是可以有很多个的,我们在web.xml中如下配置就可以引入它们:

    
SprongBoot默认已经配置好了Spring,它的内部相当于已经有一个配置文件,那个我们可以通过注解@ImportResource引入新添加配置文件

public class Address {
    private long id;
    private String detail;

}

  注意: Address类 注解@Component 与下面测试不要重复使用。

1)创建一个新的spring配置文件(简单注入一个bean):

<?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="address" class="cn.jq.springbootdemo1.springbootdemo1.model.Address"></bean>
</beans>


2)程序主类入口上添加注解@ImportResource

@SpringBootApplication
@ImportResource("classpath:spring.xml")
public class Springbootdemo1Application {

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

}

3)运行测试类(读到对象信息即OK):

@RunWith(SpringRunner.class)
@SpringBootTest
public class Springbootdemo1ApplicationTests {

    @Autowired
    private User user;

    @Autowired
    private Address address;

    @Test
    public void contextLoads() {
        System.out.println("user===" + user);
        System.out.println("address===" + address);
    }

}

   

2、SpirngBoot的配置类(推荐使用)
     SpringBoot 推荐尽可能全部用注解完成配置,所有它使用了一种配置类”来替代上面的spring的xml配置文件。


1)定义一个类做为配置类,用这个配置类代替spring.xml,所有他们之间存在一个一一对应的关系
删除上面的spring的xml配置文件和程序主类入口上添加的注解@ImportResource,创建配置类

@Configuration
public class AddressConfig {

    @Bean
    public Address address(){
        return new Address();
    }
}

2)同样运行测试类,若读到对象信息即OK:结果通上面相同

 

ends ~

 


版权声明:本文为qq_42402854原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。