SpringBoot中.properties文件绑定

SpringBoot中.properties文件绑定

两种方式

1、方式一:@ConfigurationProperties + @Component

  • @ConfigurationProperties是springboot提供读取配置文件的一个注解
  • @component是spring中的一个注解,它的作用是实现bean的注入

示例:

/**
 * 方式一:
 * 1、只有在容器中的组件才会拥有 SpringBoot提供的强大功能,所以用@Component 先把他放在容器中
   2、mycar是在 application.properties文件中自己命名的 
      mycar.brand=BYD
      mycar.price=100000
 */
@Data
@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {
    private String brand;
    private Integer price;
}

application.properties文件

server.port=8080
mycar.brand=BYD
mycar.price=100000
debug=true

在这里插入图片描述
这里运行出来,就可以在页面上获取到 car的 值了

2、方式二:@EnableConfigurationProperties+ @ConfigurationProperties

  • @EnableConfigurationProperties注解的作用是:使 某个使用 @ConfigurationProperties 注解的类生效
  • @ConfigurationProperties是springboot提供读取配置文件的一个注解

示例:

/**
 * 方式二:
 * 2、得在配置类中写,让Car里面@ConfigurationProperties(prefix = "mycar")这个属性配置生效
      注意:这个prefix 必须小写,不然会报错  (配置类就是 配置 注入bean的类)
 */
@Data
//@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {
    private String brand;
    private Integer price;
}

在这里插入图片描述

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值