Springboot (01) properties配置文件属性注入java类

一、Spring中的方式

application.properties

  1. 如果配置文件是application.properties,项目启动时会自动扫描到,直接通过@Value注入到bean中即可。例子如下:
    (1) application.properties
    xxx.id=007
	xxx.name=小明来了
	xxx.sex=男孩子

(2)实体类 XxxConfig.java

@Component
public class XxxConfig {
    @Value("${xxx.id}")
    private Integer id;
    @Value("${xxx.name}")
    private String name;
    @Value("${xxx.sex}")
    private String sex;
    //此处省略 getter,setter,toString

(3)测试类输出测试下
在这里插入图片描述

自定义properties属性

  1. 自定义properties配置文件项目启动不会加载,需要通过@PropertySource注解

xxx2.properties

xxx2.id=0072
xxx2.name=小明来了2
xxx2.sex=男孩子2

Xxx2Config.java

@Component
@PropertySource("classpath:xxx2.properties")
public class Xxx2Config {
    @Value("${xxx2.id}")
    private Integer id;
    @Value("${xxx2.name}")
    private String name;
    @Value("${xxx2.sex}")
    private String sex;
    //此处省略 getter,setter,toString

二、boot中的方式

上面通过Spring的配置方式,如果属性特别多,配置起来工作量大且容易出错,boot中有了更好的方式来避免;

通过@ConfigurationProperties注解来配置前缀,如下示例:

BootConfig.java

@Component
@PropertySource("classpath:boot.properties")
@ConfigurationProperties(prefix = "gg")  //boot为前缀
public class BootConfig {//属性名要与配置文件后缀一致
    private int id;
    private String name;
    private String sex;
    //此处省略 getter,setter,toString

boot.properties

gg.id=009
gg.name=小明来了boot
gg.sex=男孩子boot

源码已上传 https://gitee.com/shuaidawang/SpringBoot

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

臭小子帅

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

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

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

打赏作者

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

抵扣说明:

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

余额充值