Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is different between using expand() in UriComponentsBuilder and Add value directly?

Tags:

java

spring

web

What is different between using expand() in UriComponentsBuilder and Add value directly?

//#1 
String uri = UriComponentsBuilder.fromUriString(someUrl)
                .path("/" + var1 + "/path1/" + var2)
                .build();
                .toUriString();

//#2 
Map<String, Object> pathVariableMap = new HashMap<>();
pathVariableMap.put("var1", "var1");
pathVariableMap.put("var2", "var2");

String uri = UriComponentsBuilder.fromUriString(someUrl)
                .path("/{var1}/path1/{var2}")
                .buildAndExpand(pathVariableMap)
                .toUriString();

So, Why we use expand() for build URI? for readability?

like image 451
상경하 Avatar asked Oct 20 '25 04:10

상경하


1 Answers

From the official Spring Framework site, the build() and buildAndExpand() method will perform different operation based on the arguments.

Case #1

It will create a UriComponents instance from the various components contained in this builder. In your case components are like someurl and path, these component will bind together and create the instance of the UriComponent using the build() method.

Case #2

buildAndExpand(java.util.Map<java.lang.String,?> uriVariables) , this method Build a UriComponents instance and replaces URI template variables with the values from a map.

In your case your map contains

Map<String, Object> pathVariableMap = new HashMap<>();
pathVariableMap.put("var1", "var1");
pathVariableMap.put("var2", "var2");

When your creating a instance for UriComponents like this,

String uri = UriComponentsBuilder.fromUriString(someUrl)
            .path("/{var1}/path1/{var2}")
            .buildAndExpand(pathVariableMap)
            .toUriString();

so, it will replace the value of key {var1} with the value from the map var1. So your path value will become like this /var1/path1/var2.

the main difference is that, it is very useful to use buildAndExpand() is that their value is restricted to a particular element.

for Ex:

This buildAndExpand() will be very helpful when we would like to pass model objects to the Spring Controller based on which we’ll build a final URI.

For more info, UriComponentsBuilder

like image 70
Arvind Katte Avatar answered Oct 21 '25 19:10

Arvind Katte



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!