简体   繁体   中英

Access Environment based application.properties file in class not managed by spring

I am working on spring boot project having version 2.1.6.RELEASE and xslt 1.0.

I have a class that has a set of static methods used to generate the set of URL's using custom logic related to the application.

public class URLGenerator{

    public static String generateURLA(String param1,String param2,String param3)
    {
        String restServiceUrl=<acess url from application.properties>
        //code to invoke third party service
        RestTemplate restTemplate=new RestTemplate();
        String url=restTemplate.invoke()
        return url;
    }
}

In the above method, I have to make a rest call to third party service to retrieve the final URL. The URL to invoke the service is different for every environment so I have stored the URL inside the application-{env}.properties file.

I will not be able to change the above method to non static as there are several xsl files invoke the above method.

What is the best way to access the environment based application.properties file in class which is not managed by Spring?

You can simply autowire Environment and get the property:

@Autowired
private Environment env;

public void method() {
    String url = env.getProperty("service.url");
    // ...
}

If it's not a bean, you can simply create a service, that does that:

@Service
class PropertyService implements InitializingBean {

    @Autowired
    private Environment env;

    private static PropertyService instance;

    public void method() {
        String url = env.getProperty("service.url");
        // ...
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        instance = this;
    }

    public static PropertyService get() {
        return instance;
    }
}

You can use plain old properties here.

final Properties props = new Properties();
props.load(new FileInputStream("/path/application.properties"));
props.getProperty("urls.foo"));
props.getProperty("urls.bar"));

OR

final Properties props = new Properties();
try (InputStream is = getClass().getResourceAsStream("application.properties")) {
  props.load(is);
  props.getProperty("urls.foo"));
  props.getProperty("urls.bar"));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM