Stellar Sword
Stellar Sword

Reputation: 6226

Java Spring Boot Configurations & Components

I'm trying to use a component to load up my configuration yml file.

However, it throws a Null Pointer exception and System.out shows 'null' for application.

However, when the same pattern is used to code up a @RestController, everything works fine. Why is @component not seeing my configurations??

@Component
@ConfigurationProperties(prefix = "myconf")
public class AppConfigJSON {

    private String application;
    private final String applicationConfigJSON;
    Logger logger = LoggerFactory.getLogger(this.getClass());

    private final ReadContext acRcJson;

public AppConfigJSON(){
        String json = "";
        try {
            System.out.println("Application: " + this.application);
            json = IOUtils.toString(this.getClass().getResourceAsStream("/myconfs/"+this.application+".json"));
        } catch (IOException e) {
            logger.error("Error reading JSON or app YML {}", e.getStackTrace());            
        }
        this.applicationConfigJSON = json;
        this.acRcJson = JsonPath.parse(this.getApplicationConfigJSON());
    }


// These functions below set by configuration
public String getApplication()
{
    return application;
}

public void setApplication(String application)
{
    this.application = application;
}

}

Upvotes: 1

Views: 74

Answers (1)

artemisian
artemisian

Reputation: 3106

In your constructor the application variable hasn't been initialized yet, in other words, Spring needs an instance first so it can apply it's magic. You need to move your constructor logic to a method annotated with @PostContruct so the application variable is set with the property value at that point.

Upvotes: 2

Related Questions