0

I have the following configuration class for setting custom application.properties 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;
    }

}

In my application.properties I have

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

I try to use the property in the following class

@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);
    }
}

However parseAddressProperties.getEndpoint() returns null

Any idea what I am doing wrong?

david
  • 997
  • 3
  • 14
  • 34
  • I just copy-pasted that code within a new Spring boot project, and it works fine. Can you tell us what Spring boot version you're using? – g00glen00b Dec 10 '19 at 07:12
  • The issue was that I was creating the AddressParser object with "new" instead of Autowired – david Dec 10 '19 at 11:39

2 Answers2

1

The issue was that I was creating the AddressParser object with "new" instead of Autowired

david
  • 997
  • 3
  • 14
  • 34
0

Usually class annotated with @ConfigurationProperties is a simple POJO. Its registered in Configuration annotated classes. So please try the following approach:

  1. Put the following line into src/main/resources/application.properties or src/main/resources/config/application.properties:
app.properties.parseaddress.endpoint=http://myurl.com:5000/parseAddress
  1. Rewrite Configuration Properties class to be a 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. Create a Configuration class/reuse the existing one:

@Configuration
@EnableConfigurationProperties(ParseAddressProperties.class)
public class MyConfiguration {
 ...
}
Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97