1

I have a Spring Boot application with the below application.properties:

message=default1
security.url=defaultSecurityURL.com
security.authMethod=defaultAuth
security.roles=USER,ADMIN,PARTNER  
message_temp=dummyvaluehere 

Now, I have a Java class that reads all these variables from the application.properties:

@ConfigurationProperties 
@ConstructorBinding
public final class EnvConfig {

    private final String message;
    private final Security security; //there is a Security class defined seperately
    private final String messageTemp;
    
    public EnvConfig(String message, Security security, String messageTemp) {
        super();
        this.message = message;
        this.security = new Security(security.getUrl(), security.getAuthMethod(), security.getRoles()); //this is done for immutability
        this.messageTemp = messageTemp;
    }

    public String getMessage() {
        return message;
    }
    public Security getSecurity() {
        return security;
    }
    public String getMessageTemp() {
        return messageTemp;
    }

    @Override
    public String toString() {
        return "EnvConfig [message=" + message + ", security=" + security + ", messageTemp="
                + messageTemp + "]";
    }
}

Everything works fine. Now I want to add 2 more variables to my application.properties file:

message.default.app.deploy.strategy=bg
message.default.app.deploy.retries=3

But I don't want to read these variables by declaring a new class (like I created a Security class above). How can I read these values in my EnvConfig class?

HoRn
  • 1,458
  • 5
  • 20
  • 25
Kush Sharma
  • 39
  • 2
  • 9
  • I assume you are looking for [`@Value`](https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-value-annotations) annotation – R.G Dec 30 '20 at 16:23
  • I used @Value in constructor parameters and Autowired annotation at constructor level. But it prints null values for these 2 variables. So it didn't work out for me. – Kush Sharma Dec 30 '20 at 16:28

1 Answers1

0

Look in my answer of this SO question which offers a generic way to access all variables of the spring environment (by its string key).

Heri
  • 4,368
  • 1
  • 31
  • 51
  • I think my approach is better. I fixed it by adding @Value annotations for 2 new variables at instance variable level. It works fine now. – Kush Sharma Dec 30 '20 at 18:19