Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to externalize a url in Spring Boot to application.properties file?

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 :)

like image 956
user1340582 Avatar asked Feb 07 '16 19:02

user1340582


3 Answers

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!
}
like image 193
patrykos91 Avatar answered Nov 27 '22 06:11

patrykos91


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");
    }
}
like image 20
Xtreme Biker Avatar answered Nov 27 '22 05:11

Xtreme Biker


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;
like image 24
Prabu M Avatar answered Nov 27 '22 05:11

Prabu M