0

I'm adding some system properties inside a @PostConstruct decorated method of a bean like shown below :

@Profile("dev")
@Component
public class DeveloppementPropertySetter {

    @PostConstruct
    public void setProperty() {
        System.setProperty("ip", "X.X.X.X");
        System.setProperty("port", "1234");
    }
}

And when I try to get those properties from another bean (in another class) :

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
  String ip = System.getProperty("ip");
  String port = System.getProperty("port");
  (... using port and ip to customize the builder ...)
}

I got NullPointerException and spring fails to instantiate restTemplate bean. How can I make sure that the bean DeveloppementPropertySetter get initialized before restTemplate ? I do not want to use @DependsOn annotation.

Parison
  • 179
  • 1
  • 2
  • 8

1 Answers1

0

@DependsOn appears to be the answer to your problem.

If you add @DependsOn to the restTemplate, then Spring will guarantee that the DeveloppementPropertySetter bean will be fully initialized before it attempts to create the restTemplate.

"I do not want to use @DependsOn" is in no way a valid statement.

The DeveloppementPropertySetter bean must be fully initiaized before the RestTemplate is created, yet the DeveloppementPropertySetter is not injected into the RestTemplate bean. This situation appears to be exactly why the @DependsOn annotation was created.

DwB
  • 37,124
  • 11
  • 56
  • 82