Home > database >  Spring Boot Environment Variable in Config does not resolve
Spring Boot Environment Variable in Config does not resolve

Time:12-27

I have the following application.properties where I have a Service definition

service.user=${SERVICE_USER}
service.password=${SERVICE_PASSWORD}
service.url=http://someurl.com/api

In the Environment I then specify User and Password

SERVICE_USER=test
SERVICE_PASSWORD=test

The configurations is read in as follows

@Configuration
@ConfigurationProperties(prefix = "service")
public class ServiceConfiguration {

    private String url;

    private String user;

    private String password;

    // setters and getters
}

The issue is that ${SERVICE_PASSWORD} seems not to be resolved. When checking in Debugger it's exactly the value of the variable password. Therefor I can't connect to the Service as it gives the Error "Authentication failed". When I enter the values directly like

service.user=test
service.password=test
service.url=http://someurl.com/api

everything works as expected. Must Environment Variables, that are needed in the Code, be read in directly?

CodePudding user response:

You can refer below configuration to read values from properties file.

@Configuration
public class ServiceConfiguration {

    @Value("${service.url}")
    private String url;

    @Value("${service.user}")    
    private String user;

    @Value("${service.password}")    
    private String password;
}

CodePudding user response:

You can use prefix and do the same like this:

@Configuration

@ConfigurationProperties(prefix = "service")

public class ServiceConfiguration {
@Value("${url}")  
private String url;
@Value("${user}")  
private String user;
@Value("${password}")  
private String password;}
  • Related