The Spring Web Flux provides different applications to developers to develop asynchronous, non-blocking web applications by using Mono, Flux, and other classes. In this article, we will be learning to write a basic Hello World program in Spring WenFlux.
Project Creation:
- Open STS (Spring Tool Suite) and then select New Project.
- After that, we will be redirected to a project creation screen, in Select Project Category like maven or gradle, choose any (Here we will be using Gradle).
- Then provide the project name, package name, and other details.
- Then select dependencies.
- Now click on finish.
Project Folder Structure:
Project Dependencies:
In this project, we have used below dependencies and the project category is gradle.
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-webflux'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'io.projectreactor:reactor-test'
}
Hello World Program in Spring WebFlux
Here, we have provided a basic example for printing Hello World by using @RestController.
- For this, in main package, we have created one Java class named as HelloWorldController.
- After that, we have created one @GetMapping end point with name hello.
- The @GetMapping is used for creating API End points.
- While open with browser, this return output as Hello, World!.
HelloWorldController class:
package com.app;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
@RestController public class HelloWorldController {
@GetMapping ( "/hello" )
public Mono<String> hello() {
return Mono.just( "Hello, World!" ); //prints Hello, World!
}
} |
Main Class:
This is a main class of the project.
package com.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication public class HelloWorldApplication {
// Main Method
public static void main(String[] args) {
SpringApplication.run(HelloWorldApplication. class , args);
}
} |
After successfully running this project as Spring Boot App, open any browser then type below API End Point URL:
http://localhost:8080/hello
Output:
Below we can see the output in browser.
Explanation of the above Program:
- First, we have created one class in main package of project.
- The class name is HelloWorldController.
- After this, we have created one Get Mapping by using @GetMapping with parameter /hello.
- Next, we run this project as Spring Boot Application.
- After running, open browser then type the Get mapping URL that is provided in the above.
- Once hit that API end point, we got the expected output that is visible in the output screen.