get external url from application.properties with pathvariable

141 Views Asked by At

I have a situation were i need to call an external endpoint. I am using spring boot. I have placed the endpoint in the application.properties file and used a placeholder for the parameter I need to change like so: messageapi=http://localhost:8080/uxt/get/{{userId}}/messages/notification

where userid is a dynamic value generated in code.

what is the most efficient way for me to to access this value in asyncRestTemplate.exchange() method and replace the variable?

2

There are 2 best solutions below

0
On BEST ANSWER

This how i would approach it. I would plase a string placeholder, get it with @Value and then I would use String.format. So here it goes:

  • Step 1 use this format in your application.properties file entry messageapi=http://localhost:8080/uxt/get/%s/messages/notification

  • Step 2 in your class use the

    @Value("${messageapi}")
    String messageapi;
    

and store the value

  • Step 3 use the following to replace the userId String.format(messageapi,"userId ")); and in your case somthing like

    asycTemp.exchange(String.format(messageapi,"userId ")), method, requestEntity, responseType);
    

I hope I helped

0
On

To add to the already accepted answer, you can do this with a combination of the @Value annotation, SpEL, and request scoped beans.

Consider this implementation

@Value("#{T(java.lang.String).format('${messageapi}', T(org.springframework.security.core.context.SecurityContextHolder).getContext().authentication.name)}" )
private String messageApiURL;

Add that to a service that's scoped with request, that's called from another request scoped bean. This pulls the user from the active security context, but you could put any method here that you can reach, you can even call methods from other beans that are not request scoped, like this:

@Value("#{T(java.lang.String).format('${messageapi}', {userService.getUser()})}" )
private String prop;

This would call the getUser() method on a bean named userService, passing it as an arg to the String format.