Spring Boot微服务从yml文件中加载配置(使用@Value和@ConfigurationProperties)

文章介绍了如何在SpringBoot2.6.3中使用@Value和@ConfigurationProperties注解从application.yml加载配置。@Value用于加载单个配置值,而@ConfigurationProperties可以将一组相关配置映射到Java对象。示例包括加载普通对象、List类型以及静态属性的方法,并展示了在Controller中的应用。

记录:398

场景:在Spring Boot的微服务中从application.yml等yml文件中加载自定义配置内容。使用@Value直接加载单个配置。使用@ConfigurationProperties注解把一个或者多个配置加载为Java对象。

版本:JDK 1.8,SpringBoot 2.6.3

1.使用@Value注解加载配置

使用注解@RestController、@Service、@Component等标记的类中,都可以使用@Value注解从yml文件中加载配置取值。

1.1在yml文件配置

hub:
  example:
    city-name: '杭州'

1.2使用@Value取值

 @Value("${hub.example.city-name}")
 private String cityName;

2.从yml文件加载配置为普通Java对象

在Java类上,加@ConfigurationProperties注解,实现从yml文件加载配置为普通Java对象。

注解@ConfigurationProperties的属性prefix是指定扫描yml文件中的配置的前缀。

注解@Component指定该类交给Spring创建Bean对象。

使用时,在类变量上加@Autowired直接注入就可以取值。

2.1在yml文件配置

hub:
  example:
    city:
      city-id: 330100
      city-name: '杭州'

2.2对应Java类

@Component
@ConfigurationProperties(prefix = "hub.example.city")
public class CityProperties {
  private Long cityId;
  private String cityName;
  public Long getCityId() {
      return cityId;
  }
  public void setCityId(Long cityId) {
      this.cityId = cityId;
  }
  public String getCityName() {
      return cityName;
  }
  public void setCityName(String cityName) {
      this.cityName = cityName;
  }
  public String toString() {
      return "CityProperties(cityId=" + cityId + ",cityName=" + cityName + ")";
  }
}

3.从yml文件加载配置为List类型

在Java类上,加@ConfigurationProperties注解,实现从yml文件加载配置为List类型。

注解@ConfigurationProperties的属性prefix是指定扫描yml文件中的配置的前缀。

注解@Component指定该类交给Spring创建Bean对象。

使用时,在类变量上加@Autowired直接注入就可以取值。

3.1在yml文件配置

在yml文件中的短横线"-"代表是List类型属性。

hub:
  example:
    province:
      province-id: 330000
      province-name: '浙江'
      city-list:
        - city-id: 330100
          city-name: '杭州'
        - city-id: 330201
          city-name: '宁波'

3.2对应Java类

@Component
@ConfigurationProperties(prefix = "hub.example.province")
public class ProvinceProperties {
  private Long provinceId;
  private String provinceName;
  private List<CityProperties> cityList;
  public Long getProvinceId() {
    return provinceId;
  }
  public void setProvinceId(Long provinceId) {
    this.provinceId = provinceId;
  }
  public String getProvinceName() {
    return provinceName;
  }
  public void setProvinceName(String provinceName) {
    this.provinceName = provinceName;
  }
  public List<CityProperties> getCityList() {
    return cityList;
  }
  public void setCityList(List<CityProperties> cityList) {
    this.cityList = cityList;
  }
  public String toString() {
    return "ProvinceProperties(provinceId=" + provinceId + ",provinceName=" + provinceName +",cityList=" +cityList.toString()+")";
  }
}

4.从yml文件加载配置为static属性

在Java类上,加@ConfigurationProperties注解,实现从yml文件加载配置赋值给Java类的static属性。

注解@ConfigurationProperties的属性prefix是指定扫描yml文件中的配置的前缀。

注解@Component指定该类交给Spring创建Bean对象。

使用时,直接使用类名加属性名或者类名加方法名就可以取值。

4.1在yml文件配置

hub:
  example:
    static-city:
      city-id: 330201
      city-name: '宁波'

4.2对应Java类

在Java类中,属性必须是static修饰。get方式必须是static修饰。set方法不能使用static修饰。

@Component("staticCityProperties")
@ConfigurationProperties(prefix = "hub.example.static-city")
public class StaticCityProperties {
  private static Long cityId;
  private static String cityName;
  public static Long getCityId() {
    return cityId;
  }
  public void setCityId(Long cityId) {
    StaticCityProperties.cityId = cityId;
  }
  public static String getCityName() {
    return cityName;
  }
  public void setCityName(String cityName) {
    StaticCityProperties.cityName = cityName;
  }
}

5.应用

本例在Controller类中应用以上功能。

5.1应用

@RestController
@RequestMapping("/hub/example/load")
@Slf4j
public class LoadController {
  //使用@Value加载yml配置
  @Value("${hub.example.city-name}")
  private String cityName;
  //使用@Autowired注入属性
  @Autowired
  private CityProperties city;
  @Autowired
  private ProvinceProperties province;
  @PostMapping("/loadData")
  public Object loadData() {
    log.info("1.使用@Value从yml文件加载配置: " + cityName);
    log.info("2.从yml文件加载配置为普通Java对象: " + city.toString());
    log.info("3.从yml文件加载配置为List类型: " + province.toString());
    log.info("4.从yml文件加载配置为static属性: " + StaticCityProperties.getCityName());
    return "执行成功";
  }
}

5.2输出结果

1.使用@Value从yml文件加载配置: 杭州
2.从yml文件加载配置为普通Java对象: CityProperties(cityId=330100,cityName=杭州)
3.从yml文件加载配置为List类型: ProvinceProperties(provinceId=330000,provinceName=浙江,cityList=[CityProperties(cityId=330100,cityName=杭州), CityProperties(cityId=330201,cityName=宁波)])
4.从yml文件加载配置为static属性: 宁波

以上,感谢。

2023年4月11日

<think>我们正在讨论的是在Spring Boot使用@Value加载自定义属性文件的方法。根据引用[1],我们知道Spring Boot允许自定义属性配置。引用[2][3]详细说明了在Spring Boot使用@Value注解的步骤,以及如何加载自定义属性文件。引用[4]则给出了一个使用@Value注解获取自定义属性并赋值给变量的示例。 具体步骤如下: 1. **创建自定义属性文件**:在`src/main/resources`目录下创建自定义属性文件,例如`myconfig.properties`,并添加属性: ```properties custom.file.path=/path/to/custom/file.txt ``` 2. **使用`@PropertySource`注解加载自定义属性文件**:在需要注入属性的类上使用`@PropertySource`注解指定文件路径。注意,`@PropertySource`默认不支持`*.properties`文件以外的类型,且不支持使用YAML文件[^3]。 ```java @Component @PropertySource("classpath:myconfig.properties") public class MyConfig { // ... } ``` 如果需要加载多个文件,可以使用: ```java @PropertySource({"classpath:config1.properties", "classpath:config2.properties"}) ``` 注意:如果多个文件中有相同的属性名,则后面文件中的属性值会覆盖前面的。 3. **使用`@Value`注解注入属性值**:在类的字段上使用`@Value("${属性名}")`来注入值。 ```java @Value("${custom.file.path}") private String filePath; ``` 4. **注意事项**: - 确保类被Spring管理(例如使用`@Component`、`@Service`等注解)。 - 如果属性文件中有占位符(如`${another.property}`),Spring Boot会自动解析,但需要确保被引用的属性也在同一个或已加载的属性文件中。 - 如果自定义属性文件不在classpath下,可以使用`file:`前缀指定绝对路径,例如:`@PropertySource("file:/absolute/path/to/config.properties")`。 5. **Spring Boot的默认配置**:Spring Boot默认会加载`application.properties`或`application.yml`文件,所以如果自定义属性不多,可以直接放在这些默认文件中,无需使用`@PropertySource`。 示例代码: ```java @Component @PropertySource("classpath:myconfig.properties") public class FileService { @Value("${custom.file.path}") private String filePath; public void printFilePath() { System.out.println("文件路径: " + filePath); } } ``` 如果遇到属性无法注入的问题,请检查: - 属性文件是否正确加载(可通过在启动日志中查看) - 属性名称是否正确 - 类是否被Spring扫描到 相关问题: 1. 如何在Spring Boot加载多个自定义属性文件? 2. 如果自定义属性文件中的属性值包含特殊字符(如冒号、空格),如何处理? 3. 如何在Spring Boot测试中加载自定义属性文件? </think>### Spring Boot使用@Value加载自定义属性文件的方法 在Spring Boot中,使用`@Value`注解加载自定义属性文件需配合`@PropertySource`注解实现。以下是具体步骤(参考引用[1][2][3][4]): --- #### 1. **创建自定义属性文件** 在`src/main/resources`目录下创建`.properties`文件(如`custom.properties`)并添加属性: ```properties # custom.properties app.name=MySpringBootApp file.export.path=/data/exports max.retry.count=5 ``` --- #### 2. **使用@PropertySource加载文件** 在配置类或组件类上添加注解指定文件路径: ```java @Configuration @PropertySource("classpath:custom.properties") // 加载类路径文件 public class AppConfig { // 可添加其他配置 } ``` > **注意**: > - 支持加载多个文件:`@PropertySource({"file1.properties", "file2.properties"})` > - 非默认路径文件需用`file:`前缀:`@PropertySource("file:/abs/path/config.properties")`[^3] --- #### 3. **使用@Value注入属性值** 在Spring管理的Bean中直接注入: ```java @Service public class FileService { // 基本类型注入 @Value("${file.export.path}") private String exportPath; // 数值类型注入 @Value("${max.retry.count}") private int maxRetries; } ``` --- #### 4. **处理特殊场景** ##### (1) 默认值设置 当属性不存在时提供默认值: ```java @Value("${app.version:1.0.0}") // 若未定义则使用1.0.0 private String appVersion; ``` ##### (2) 嵌套属性解析 自动解析属性中的占位符: ```properties # custom.properties user.home=${HOME}/app-data # 引用系统环境变量 ``` ```java @Value("${user.home}") private String userHomeDir; // 输出: /Users/username/app-data ``` ##### (3)文件属性覆盖 当多个文件存在同名属性时,**最后加载文件优先级最高**: ```java @PropertySource({"config1.properties", "config2.properties"}) // config2的属性会覆盖config1 ``` --- #### 5. **验证配置加载** 在`application.properties`中启用配置调试: ```properties # application.properties debug=true ``` 启动应用时控制台将显示: ```bash Loaded properties: custom.properties file.export.path=/data/exports max.retry.count=5 ``` --- ### 常见问题解决 1. **属性未注入** - 检查文件路径是否正确(`classpath:` vs `file:`) - 确认类有`@Component`或`@Service`注解 - 查看启动日志是否加载了目标文件 2. **属性值包含特殊字符** 用单引号包裹属性值: ```properties special.path='C:\Program Files\data' ``` 3. **动态刷新属性** 需配合`@RefreshScope`实现热更新(需Spring Cloud支持)。 --- ### 相关问题 1. 如何在Spring Boot加载YAML格式的自定义配置文件? 2. `@PropertySource``@ConfigurationProperties`有什么区别? 3. 如何实现根据不同环境(dev/test/prod)加载不同的自定义属性文件? > 参考文档: > [^1]: Spring Boot自定义属性配置机制 > [^2]: `@Value`与传统Spring框架的区别 > [^3]: `@PropertySource`的多文件加载规则 > [^4]: `@Value`注解的实际应用示例
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值