@PropertySource、@ImportSource和@Bean

一、 @PropertySource

正常情况下@ConfigurationProperties读取的是全局配置文件(工程创建成功后自带的application.properties文件),假如我的javaBean相关的配置不在全局配置文件中配置,而是在自己写的局部配置文件中,此时就要用到@PropertySource来加载指定的配置文件。例如我将之前在全局配置文件中写的配置信息注释,在自己新建的一个配置文件中重新配置,person.properties的配置信息如下:

#配置person的值
person.last-name=李四
person.age=18
person.birth=2017/12/15
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=guang
person.dog.age=26

在javaBean中使用时,可以这样使用:

@PropertySource(value = {"classpath:person.properties"})
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
//    @Value("${person.last-name}")
    private String lastName;
//    @Value("${person.age}")
    private Integer age;
    private Boolean boss;
    private Date birth;

    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;

二、@ImportSource

导入Spring的配置文件,让配置文件的内容生效。

这里写了一个spring的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.atguigu.springboot.service.HelloService"></bean>
</beans>

为了让此配置文件生效,我们需要将@ImportSource标注在一个配置类上,这里标注在主配置类上,即在SpringBootApplication中加上注解@ImportSource,如下所示:

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

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

}

SpringBoot推荐给容器中添加组件的方式:推荐使用全注解的方式

1、写一个配置类=======Spring配置文件

配置类MyAppConfig 的内容:

/**
 * @Configuration:指明当前类是一个配置类,替代之前的Spring配置文件
 */
@Configuration
public class MyAppConfig {
    //@Bean:将方法的返回值添加到容器中,容器中这个组件默认的id就是方法名
    @Bean
    public HelloService helloService(){
        System.out.println("配置类@Bean给容器中添加组件成功");
        return new HelloService();
    }
}

完整代码见:

https://github.com/13029403279/Study/upload/master

下的spring-boot-config

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值