Spring boot 十四 读取 .properties 配置

本文介绍SpringBoot中多种配置属性读取方法,包括使用@Value注解读取简单类型属性、通过@ConfigurationProperties读取复杂对象及List集合,还涉及静态对象及List对象的配置读取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一种 属性读取
第二种 类读取。
第三种 读取List方式:
第四种 读取List<对象>:

出现下面的问题:
在这里插入图片描述
可以忽略,如果你觉的看着不舒服,可以点击进去复制他的依赖 添加到 pom 里面就好。
在这里插入图片描述

属性读取。

1、在application.properties 中添加 要读取的配置:

hello = hello world

2、属性上 添加 (@Value("${hello}"))

@RestController
public class UserController{

    @Value("${hello}")   //如果是  多级,可以用 '.' 来连接("${xxx.xxx.xxx}")
    private String  helloText;

    @RequestMapping("/hello")
    public String hello(){
        return helloText;
    }
}

类读取。

1、在src/main/resource。创建custom.properties文件:

    user.name=zll
    user.age=32
    user.score=98.5

2、创建读取类

@Component
@PropertySource(value = "classpath:custom.properties",encoding = "utf-8")
@ConfigurationProperties("user")
@Data
public class UserDto {

    private String name;
    private int age;
    private double score;
}

读取List方式:

custom.properties

country.city[0]=bj
country.city[1]=上海
country.city[2]=shengZheng
country.city[3]=温江

读取方式

@Component
@PropertySource(value = "classpath:custom.properties",encoding = "utf-8")
@ConfigurationProperties("country")
@Data
public class CountryDto {

    private List<String> city;
}

读取静态对象方式:
需要给静态属性设置 set方法:

@Component
public class BaseConfig {
    public static String BASE_URL;
    @Value("${server.servlet.context-path}")
    public void setBaseUrl2(String path) {
        BASE_URL = path;
    }
}

读取List<对象>:

custom.properties 中

group.user[0].name=张三
group.user[0].age=18
group.user[1].name=李四
group.user[1].age=19
group.user[1].score=99
group.user[2].name=王五
group.user[2].score=82.2

读取方式:

@Component
@PropertySource(value = "classpath:custom.properties",encoding = "utf-8")
@ConfigurationProperties("group") //这里 必须填写 属性的开始名称 group.user[0].name=张三
@Data
public class UserListDto {

//    属性名必须和 自定义 温江里面的 名字一样 group.user[0].name=张三
    List<User> user;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值