JAVA Spring Boot : How to access application.properties values in normal class

Viewed 8307

I know how I can access the application.properties values in @Service classes in Java Spring boot like below

@Service
public class AmazonClient {

    @Value("${cloud.aws.endpointUrl}")
    private String endpointUrl;
}

But I am looking for an option to access this value directly in any class (a class without @Service annotation)

e.g.

public class AppUtils {
      @Value("${cloud.aws.endpointUrl}")
      private String endpointUrl;
}

But this returns null. Any help would be appreciated. I have already read here but didn't help.

2 Answers

There's no "magic" way to inject values from a property file into a class that isn't a bean. You can define a static java.util.Properties field in the class, load values from the file manually when the class is loading and then work with this field:

public final class AppUtils {
    private static final Properties properties;

    static {
        properties = new Properties();

        try {
            ClassLoader classLoader = AppUtils.class.getClassLoader();
            InputStream applicationPropertiesStream = classLoader.getResourceAsStream("application.properties");
            applicationProperties.load(applicationPropertiesStream);
        } catch (Exception e) {
            // process the exception
        }
    }
}
Related