自定义ConfigurationProperties类,返回null

时间:2019-12-10 04:13:53

标签: spring-boot

我具有以下配置类,用于设置自定义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

知道我在做什么错吗?

2 个答案:

答案 0 :(得分:0)

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

  1. 将以下行放入src/main/resources/application.propertiessrc/main/resources/config/application.properties中:
app.properties.parseaddress.endpoint=http://myurl.com:5000/parseAddress
  1. 将“配置属性”类重写为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 {
 ...
}

答案 1 :(得分:0)

问题是我在创建AddressParser对象时使用的是“新”而不是自动装配