Anand Deshmukh
Anand Deshmukh

Reputation: 1126

In spring-boot Class constructor get called first or bootstrap.yml?

I Have a spring-boot application. I wanted to pick some values from bootstrap.yml into the constructor of the class. Below is the code Snippet.

public class MapicsSCFFGeneratorServiceImpl implements MapicsSCFFGeneratorService {

    @Value("${azuresb.nameSpace}")
    private String nameSpace;

    @Value("${azuresb.sasPolicyKeyName}")
    private String sasPolicyKeyName;

    @Value("${azuresb.sasPolicyKey}")
    private String sasPolicyKey;

    @Value("${azuresb.serviceBusRootURI}")
    private String serviceBusRootURI;

    @Value("${azuresb.queueName}")
    private String queueName;

    public MapicsSCFFGeneratorServiceImpl() {

        config = ServiceBusConfiguration.configureWithSASAuthentication(nameSpace, sasPolicyKeyName, sasPolicyKey,
                serviceBusRootURI);

    }
}

My question is Which one get call first bootstrap.yml or constructor

Because If I am printing this values inside constructor I am getting Null on the other hand outsides the constructor the values are printing.

Upvotes: 1

Views: 824

Answers (1)

davidxxx
davidxxx

Reputation: 131396

It makes sense that the constructor be invoked before the Spring processing that values the fields with Spring properties.
From a logical point of view, the constructor has to be invoked before Spring values instance fields.

As alternative, you could move the processing that uses the fields valued by Spring in a method annotated with javax.annotation.@PostConstruct.

From the specification :

The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization.

@PostConstruct
public void postProcess(){
   config = ServiceBusConfiguration.configureWithSASAuthentication(nameSpace, sasPolicyKeyName, sasPolicyKey,
                serviceBusRootURI);
}

Upvotes: 3

Related Questions