I have a REST consumer class with "url" variable. Instead of typing the endpoint url directly to the variable, I would like to externalize the actual url string to e.g. the application.properties file. So how do I then reference to the url string from the variable in code?
I know, a super easy question but I just couldn't find anything from google :)
Another, more type-safe way of doing this in SpringBoot is using @ConfigurationProperties(prefix="some_prefix")
. You declare your variable in application.properties endpoint.url=example.com
. Then in Your class you do something like:
@Service
@ConfigurationProperties(prefix="endpoint")
public class exampleClass {
private String url; //variable name has to match name of the variable definied in application.properties
//getter and setter for url is mandatory!
}
Declare it in application.properties:
service.url=http://myservice.com:8080
Then, you are supposed to have a @Service
including a RestTemplate
or similar to access the endpoint:
@Service
public class RemoteAccessService{
private RestTemplate template;
private String baseUrl;
@Autowired
public RemoteAccessService(RestTemplate template, @Value("${service.url}") baseUrl){
this.template = template;
this.baseUrl = baseUrl;
}
public String grabResult(){
return template.getForObject(baseUrl+"/hotels/{hotel}/bookings/{booking}", String.class, "42", "21");
}
}
If you are using application.yml file, will make it simpler then
services:
service: ${https://requiredUrl}
and in your class file
@Value("${services.service}")
private String reqUrl;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With