@ConfigurationProperties与@PropertySource的使用

目录

前沿

准备

使用@ConfigurationProperties

①使用@Component + @ConfigurationProperties

②@EnableConfigurationProperties + @ConfigurationProperties 

小结

使用@PropertySource

①@PropertySource +@Component+ @Value 

②使用@PropertySource 和 @ConfigurationProperties 


前沿

很多时候我们需要将配置文件的内容读取到程序中,我们可以使用@ConfigurationProperties注解也可以使用@PropertySource,那么我们该如何操作呢?

准备

springboot工程的配置文件(application.properties或application.yml)

使用@ConfigurationProperties

①使用@Component + @ConfigurationProperties

编写Controller测试

package com.aoshen.controller;

import com.aoshen.pojo.School;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class MyController {
    @Autowired
    private School school;

    @GetMapping("/school")
    public String getSchool(){
        return  school.toString();
    }
}

@EnableConfigurationProperties + @ConfigurationProperties 

只在实体类上保留@ConfigurationProperties注解

在配置类加入 @EnableConfigurationProperties注解

 这个类的作用我在上篇文章中已经讲述过,这里不再赘述。

再次启动访问我们的Controller

 

小结

上述两种方式我们必须保证实体类的属性与配置文件里的配置要保持一致

 

否则对象的属性不会自动装配,会显示为null。

使用@PropertySource

上面的方式我们可以看出,其配置信息是写在了springboot的配置文件中(application.properties或application.yml)。如果是我们自定义的配置文件我们应该如何读取呢?

①@PropertySource +@Component+ @Value 

这里实体类与配置文件里的名字可以不一致哦

启动测试

 

②使用@PropertySource 和 @ConfigurationProperties 

如果不想使用@Value注解可以借助我们的@ConfigurationProperties 注解

这里配置文件与实体类名字得一致哦

测试

 

 

  • 8
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

喜欢编程的夏先生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值