rupweb
rupweb

Reputation: 3328

get springboot application.properties env variables into config class

I am struggling to create a config class that holds final strings of configuration properties that I use elsewhere. I don't want to use the Environment. So I have some code

@Autowire
Environment env;

return this.webClient.get()
  .uri(uriBuilder -> uriBuilder.path(env.getProperty("endpoint")).build())
  .accept(MediaType.TEXT_EVENT_STREAM)
  .exchangeToFlux(e -> e.bodyToFlux(Event.class));

That's actually working fine, but I want to get my config together in a separate class, out of the environment. Like:

@Configuration
@PropertySource("classpath:application.properties")
public class MyConfig {

  @Value("${endpoint}")
  public static final String URI = "";

  @Bean
  public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
    return new PropertySourcesPlaceholderConfigurer();
  }
}

In my springboot project when I change from env to use the MyConfig variable:

return this.webClient.get()
  .uri(uriBuilder -> uriBuilder.path(MyConfig.URI).build())
  .accept(MediaType.TEXT_EVENT_STREAM)
  .exchangeToFlux(e -> e.bodyToFlux(Event.class));

When I get a unit test going that's going to run the call to the URI config from the MsgConfig class it's always null. How can I get the thing to populate?

UPDATE

It looked as if removing the static from

public static final String URI = "";

and @Autowire the MyConfig class into the other class was going to work, and indeed sometimes it does, but this appears to cause a race condition whether the URI is set or not...

Upvotes: 0

Views: 518

Answers (1)

Scott Frederick
Scott Frederick

Reputation: 5145

I would suggest using a configuration properties class, as described in the Spring Boot documentation.

First, create a class to hold the configuration properties:

@ConfigurationProperties("endpoint")
public class EndpointProperties {

    private final URI uri;

    public MyProperties(URI uri) {
        this.uri = uri;
    }

    public URI getUri() {
        return this.uri;
    }
}

Then enable the EndpointProperties using one of the techniques described in the documentation.

You can then inject this into the class that needs the properties:

@Autowired EndpointProperties endpoint;

return this.webClient.get()
  .uri(uriBuilder -> uriBuilder.path(endpoint.getUri()).build())
  .accept(MediaType.TEXT_EVENT_STREAM)
  .exchangeToFlux(e -> e.bodyToFlux(Event.class));

In a Spring Boot application.yml file, you'd set the property value like this:

endpoint: 
  uri: https://example.com/api/

Upvotes: 1

Related Questions