Reputation: 629
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?
Upvotes: 1
Views: 1239
Reputation: 175
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"));
}
Upvotes: 0
Reputation: 26026
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;
}
}
Upvotes: 2