user1340582
user1340582

Reputation: 19729

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

Upvotes: 9

Views: 27543

Answers (4)

Bhaskara Arani
Bhaskara Arani

Reputation: 1667

in the application.properties enter image description here

in the controller or service refer like this

enter image description here

Upvotes: 1

Prabu M
Prabu M

Reputation: 180

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;

Upvotes: 2

patrykos91
patrykos91

Reputation: 3686

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!
}

Upvotes: 7

Aritz
Aritz

Reputation: 31669

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");
    }
}

Upvotes: 5

Related Questions