Combining handler and router

We have written two different classes for the handler and router; however, we can declare the configuration that covers the functionality of both the router and handler in a single class. This can be done by combining the handler and router method pair in one single method as follows:

@Configuration
public class StudentRouterHandlerCombined {

@Autowired
private StudentMongoRepository studentMongoRepository;

@Bean
RouterFunction<ServerResponse> returnStudentWithCombineFun(){

HandlerFunction<ServerResponse> studentHandler =
serverRequest -> {
int rollNo = getInt(serverRequest.pathVariable("rollNo"));
return ServerResponse.ok().
body(studentMongoRepository.findByRollNo(rollNo)
, Student.class);
};

RouterFunction<ServerResponse> studentResponse =
RouterFunctions.route(
RequestPredicates.GET("/api/f/combine/getStudent/{rollNo}"),
studentHandler);

return studentResponse;
}

@Bean
RouterFunction<ServerResponse> returnAllStudentWithCombineFun(){
HandlerFunction<ServerResponse> studentHandler =
serverRequest ->
ServerResponse.ok().
body(studentMongoRepository.findAll(), Student.class);

RouterFunction<ServerResponse> studentResponse =
RouterFunctions.route(
RequestPredicates.GET("/api/f/combine/getAllStudent"),
studentHandler);

return studentResponse;
}

private int getInt(String intStr) {
int returnVal=0;
if(intStr !=null !intStr.isEmpty()) {
try {
returnVal = Integer.parseInt(intStr);
}catch(Exception e) {
e.printStackTrace();
}
}
return returnVal;
}
}

This class has two methods to fetch a single student and all students, respectively. In each method, we first create an instance of the handler and then pass it into the route() method while creating the router. The lambda expression is used to define the handler. The code is easy and straightforward. Again to make it unique, we have changed the URL pattern by adding /combine/ in between so the endpoints of getting a single student and all students can be accessed with the URL http://localhost:8080/api/f/combine/getStudent/21 and http://localhost:8080/api/f/combine/getAllStudent, respectively. You will get a similar output to when we defined handler and router separately. 

You might be wondering how this works under the hood. The bean of the RouterFunctionMapping type scans the packages and retrieves all RouterFunctions at the time of starting the application. This bean is created within WebFluxConfigurationSupport, which is the headquarters of the Spring WebFlux configuration. All these things start happening when we define the @EnableWebFlux annotation to the main bootstrap class along with the spring.main.web-application-type=reactive property.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.124.8