首页 > 解决方案 > 自定义 ConfigurationProperties 类返回 null

问题描述

我有以下用于设置自定义application.properties属性的配置类

@Component
@EnableConfigurationProperties
@ConfigurationProperties("app.properties.parseaddress")
public class ParseAddressProperties {
    private String endpoint;

    public String getEndpoint() {
        return endpoint;
    }

    public void setEndpoint(String endpoint) {
        this.endpoint = endpoint;
    }

}

在我的 application.properties 我有

app.properties.parseaddress.endpoint=http://myurl.com:5000/parseAddress

我尝试在以下类中使用该属性

@Component
public class AddressParser {
    @Autowired
    ParseAddressProperties parseAddressProperties;

    public void parseAddress(String address) throws UnsupportedEncodingException, IOException {
        JavaHttpClient httpClient = new JavaHttpClient();
        System.out.println(parseAddressProperties.getEndpoint());
        httpClient.postRequest(parseAddressProperties.getEndpoint(), "address", address);
    }
}

然而parseAddressProperties.getEndpoint()返回null

知道我做错了什么吗?

标签: spring-boot

解决方案


通常用注解的类@ConfigurationProperties是一个简单的 POJO。它在配置注释类中注册。所以请尝试以下方法:

  1. 将以下行放入src/main/resources/application.propertiesor src/main/resources/config/application.properties
app.properties.parseaddress.endpoint=http://myurl.com:5000/parseAddress
  1. 将 Configuration Properties 类重写为 POJO:
@ConfigurationProperties("app.properties.parseaddress")
public class ParseAddressProperties {
    private String endpoint;

    public String getEndpoint() {
        return endpoint;
    }

    public void setEndpoint(String endpoint) {
        this.endpoint = endpoint;
    }

}
  1. 创建一个配置类/重用现有的:

@Configuration
@EnableConfigurationProperties(ParseAddressProperties.class)
public class MyConfiguration {
 ...
}

推荐阅读