@ConfigurationProperties取properties文件值为null

一、问题内容

如题,实体类对应了properties属性文件,但是浏览器读取时,json为null。

Car.java

package com.example.pojo;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {
    private String brand;
    private Integer price;

    public String getBrand() {
        return brand;
    }

    public Car(String brand, Integer price) {
        this.brand = brand;
        this.price = price;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public Integer getPrice() {
        return price;
    }

    public void setPrice(Integer price) {
        this.price = price;
    }

    public Car() {
    }
}

configuration.properties

mycar.brand=奔驰
mycar.price = 152051

HelloController.java

@RestController
public class HelloController {

    @Autowired
    Car car;

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

浏览器截图

改掉bug后的效果: 

 

 二、解决办法

properties文件命名出错。

默认文件名:application.properties。

改过来即可解决。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
@ConfigurationProperties是一个用于获配置文件值的注解。可以通过将@ConfigurationProperties注解加到类上,然后使用方法一或方法二来获配置文件的值。方法一是将@ConfigurationProperties注解和@Component注解一起使用,通过在类上加@ConfigurationProperties注解,然后在启动类上添加@Bean方法来生成实例,并将其交由Spring容器管理。方法二是将@ConfigurationProperties注解加在@Configuration类中的@Bean方法上,通过在配置类中添加@Bean方法来生成实例,并将其交由Spring容器管理。 @ConfigurationProperties注解用于外部化配置,如果想要绑定和验证外部属性(例如从.properties文件中读的属性),可以将该注解添加到类定义或@Configuration类中的@Bean方法上。 @ConfigurationProperties注解同时支持注解和XML占位符,可以用于获配置项。它可以管理被@Value注解修饰的配置项、使用XML占位符${}修饰的配置项,以及使用@ConfigurationProperties注解修饰的配置项。通过使用@ConfigurationProperties注解,可以实现对项目配置文件的全面管理。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [【@ConfigurationProperties配置文件的值】](https://blog.csdn.net/qq_29025955/article/details/124376608)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [bridge配置管理系统-其他](https://download.csdn.net/download/weixin_38723461/19589272)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值