【SpringBoot注解】@ConfigurationProperties注解

@ConfigurationProperties主要作用就是将prefix属性指定的前缀配置项的值绑定到这个Bean上,默认情况下需要和@Component或者@Configuration一起使用才能生效。

首先回忆以下使用Java如何读取properties文件中的内容,会看到使用起来会很麻烦,SpringBoot给我们提供了更简单的方式读取Properties配置项内容。

public class getProperties {
     public static void main(String[] args) throws FileNotFoundException, IOException {
         Properties pps = new Properties();
         pps.load(new FileInputStream("a.properties"));
         Enumeration enum1 = pps.propertyNames();//得到配置文件的名字
         while(enum1.hasMoreElements()) {
             String strKey = (String) enum1.nextElement();
             String strValue = pps.getProperty(strKey);
             System.out.println(strKey + "=" + strValue);
             //封装到JavaBean。
         }
     }
 }

方式一

当配置文件中有前缀为mycar的配置内容时,会自动将其注入组件中

注意:只有在容器中的组件,才会拥有SpringBoot提供的强大功能,所以添加了@Component注解
@Data
@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {
    private String brand;
    private Integer price;

}

application.properties配置内容

mycar.brand=BYD
mycar.price=100000

通过controller层获取对象

RestController
public class HelloController {

    @Autowired
    Car car;
    @RequestMapping("/car")
    public Car car(){
        return car;
    }
}

成功注入对象里面 

 

方式二

场景:如果我们使用的是第三方jar包,就不能自己添加@Component注解,需要使用新的方式

@Data
@ConfigurationProperties(prefix = "mycar")
public class Car {
    private String brand;
    private Integer price;

}

 @EnableConfigurationProperties有两个作用:

  • 开启Car配置绑定功能
  • 把这个Car组件自动注入到容器中
@Configuration
@EnableConfigurationProperties(Car.class)
public class MyConfig {
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小鲁蛋儿

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

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

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

打赏作者

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

抵扣说明:

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

余额充值