springperformanceentityapplication.properties

get application properties values manually each file vs storing them in a single entity


I have some code in java and most of the files/functions requires retrieving values from application.properties. I'm wondering if its a good practice to store them in an entity with getters for ease of use or call them everytime I make a new file and how to possibly do it as it turns out I need to create a bean for it to work. Tried defining it in Appconfig but it showed errors.

(Disclaimer: I'm not that experienced in java)

AppConfig.java

@Configuration
public class AppConfig {
    @Bean
    public GlobalVariables globalVariables() {
        return new GlobalVariables();
    }
}

Entity with getters

@Getter
public class GlobalVariables {

    @Value("${api.id}")
    private String apiId;

    @Value("${api.key}")
    private String apiKey;

    something_else...

}
@Service
@RequiredArgsConstructor
public class SomeService {
    private final GlobalVariables globalVars;

    ...
    // Example method
    public String showApiKey() {
        return globalVars.apiKey;
    }
}

versus calling them in each service file

@Service
public class SomeService {

    @Value("${api.id}")
    private String apiId;

    @Value("${api.key}")
    private String apiKey;

    ...
    // Example method
    public String showApiKey() {
        return apiKey;
    }
}

ps: i have no idea why im doing this just wondering if this is actually a thing in java


Solution

  • The common way how to work with properties is annotation @ConfigurationProperties

    Example:

    @Data
    @FieldDefaults(level = AccessLevel.PRIVATE)
    @Validated
    @Configuration
    @ConfigurationProperties(prefix = "example.prefix")
    public class ExampleProperties {
    
        String prop1;
    
        @NotNull @Min(1) @Max(365)
        Integer prop2;
    
        boolean prop3;
    
    }
    

    Just inject ExampleProperties and get values with getters. In your config you would have example.prefix.prop1=someValue. You can have many configuration properties beans with different prefix and you can also nest classes see https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.external-config.typesafe-configuration-properties.java-bean-binding