{"id":3420,"date":"2024-09-20T15:16:38","date_gmt":"2024-09-20T13:16:38","guid":{"rendered":"https:\/\/nguenkam.com\/blog\/?p=3420"},"modified":"2024-09-20T15:16:38","modified_gmt":"2024-09-20T13:16:38","slug":"introduction-to-java-spring-boot-part-iv","status":"publish","type":"post","link":"https:\/\/nguenkam.com\/blog\/index.php\/2024\/09\/20\/introduction-to-java-spring-boot-part-iv\/","title":{"rendered":"Introduction to Java Spring Boot (Part IV)"},"content":{"rendered":"\n<p>Spring Boot has revolutionized the way developers build Java applications by providing a framework that simplifies the setup, configuration, and deployment of Spring applications. With its convention-over-configuration approach, Spring Boot allows developers to focus on writing code rather than dealing with complex configurations.<\/p>\n\n\n\n<p>In this tutorial, we will explore key concepts and features of Spring Boot, including reactive programming with Project Reactor, building RESTful APIs using <code>@RestController<\/code>, managing responses with <code>ResponseEntity<\/code>, leveraging Spring Boot Actuator for application monitoring, and securing our application with Spring Security<\/p>\n\n\n\n<h4>5. Project Reactor (Combination with Flux and Reactive Programming)<\/h4>\n\n\n\n<p><strong>What is Project Reactor?<\/strong><br>Project Reactor is a reactive programming library for the JVM, based on the Reactive Streams standard. It allows for the asynchronous processing of data streams.<\/p>\n\n\n\n<p><strong>What is Flux?<\/strong><br><code>Flux<\/code> is one of the main classes in Project Reactor, representing a sequence of 0 to N elements. It is ideal for handling multiple values that are processed asynchronously.<\/p>\n\n\n\n<p><strong>How do they work together?<\/strong><br>Project Reactor enables the creation of asynchronous, non-blocking applications using <code>Flux<\/code> and <code>Mono<\/code> (for 0 or 1 value). You can process, transform, and combine data streams efficiently.<\/p>\n\n\n\n<h4>Example<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>import reactor.core.publisher.Flux;\n\npublic class ReactorExample {\n    public static void main(String&#91;] args) {\n        Flux&lt;String&gt; flux = Flux.just(\"A\", \"B\", \"C\")\n                .map(String::toLowerCase) \/\/ Transforms each element to lowercase\n                .filter(s -&gt; s.startsWith(\"a\")); \/\/ Filters elements starting with 'a'\n\n        flux.subscribe(System.out::println); \/\/ Outputs: a\n    }\n}<\/code><\/pre>\n\n\n\n<p><strong>Explanation:<\/strong><\/p>\n\n\n\n<ul><li><code>Flux.just(\"A\", \"B\", \"C\")<\/code>: Creates a <code>Flux<\/code> from the given values.<\/li><li><code>.map(String::toLowerCase)<\/code>: Converts each string to lowercase.<\/li><li><code>.filter(s -&gt; s.startsWith(\"a\"))<\/code>: Filters the strings to only include those that start with &#8216;a&#8217;.<\/li><li><code>flux.subscribe(System.out::println)<\/code>: Subscribes to the <code>Flux<\/code> and prints each emitted item.<\/li><\/ul>\n\n\n\n<h4>6. @RestController<\/h4>\n\n\n\n<p><strong>What is a RestController?<\/strong><br>A <code>@RestController<\/code> is a specialized annotation in Spring that defines a controller whose methods return JSON or XML data directly.<\/p>\n\n\n\n<h4>Annotations<\/h4>\n\n\n\n<ul><li><strong>@GetMapping<\/strong>: Handles HTTP GET requests.<\/li><li><strong>@PostMapping<\/strong>: Handles HTTP POST requests.<\/li><li><strong>@PathVariable<\/strong>: Extracts variables from the URL.<\/li><li><strong>@RequestParam<\/strong>: Extracts parameters from the URL.<\/li><li><strong>@RequestBody<\/strong>: Binds the body of a request to a Java object.<\/li><\/ul>\n\n\n\n<h4>Example<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>import org.springframework.web.bind.annotation.*;\n\n@RestController\n@RequestMapping(\"\/api\")\npublic class MyController {\n\n    @GetMapping(\"\/hello\")\n    public String hello() {\n        return \"Hello, World!\"; \/\/ Returns a simple greeting\n    }\n\n    @PostMapping(\"\/users\")\n    public User createUser(@RequestBody User user) {\n        return user; \/\/ Returns the created user object\n    }\n\n    @GetMapping(\"\/users\/{id}\")\n    public User getUser(@PathVariable String id) {\n        return new User(id, \"John Doe\"); \/\/ Returns a user with the given ID\n    }\n\n    @GetMapping(\"\/search\")\n    public User searchUser(@RequestParam String name) {\n        return new User(\"1\", name); \/\/ Returns a user based on the search parameter\n    }\n}<\/code><\/pre>\n\n\n\n<p><strong>Explanation:<\/strong><\/p>\n\n\n\n<ul><li><code>@RestController<\/code>: Indicates that this class is a RESTful controller.<\/li><li><code>@GetMapping(\"\/hello\")<\/code>: Maps the <code>hello<\/code> method to the <code>\/hello<\/code> GET endpoint.<\/li><li><code>@PostMapping(\"\/users\")<\/code>: Maps the <code>createUser<\/code> method to the <code>\/users<\/code> POST endpoint, receiving a JSON object in the request body.<\/li><li><code>@PathVariable<\/code> and <code>@RequestParam<\/code>: Used to extract values from the URL and parameters.<\/li><\/ul>\n\n\n\n<h4>7. ResponseEntity<\/h4>\n\n\n\n<p><strong>What is it?<\/strong><br><code>ResponseEntity<\/code> is a Spring class that encapsulates the complete HTTP response, including status code, headers, and body.<\/p>\n\n\n\n<p><strong>How does this concept help us in REST API?<\/strong><br>With <code>ResponseEntity<\/code>, you can control the HTTP status code and other details of the response.<\/p>\n\n\n\n<h4>Example<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>import org.springframework.http.HttpStatus;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.*;\n\n@RestController\n@RequestMapping(\"\/api\")\npublic class UserController {\n\n    @GetMapping(\"\/users\/{id}\")\n    public ResponseEntity&lt;User&gt; getUser(@PathVariable String id) {\n        User user = findUserById(id); \/\/ Simulated method to find a user\n        if (user == null) {\n            return new ResponseEntity&lt;&gt;(HttpStatus.NOT_FOUND); \/\/ Returns 404 if user not found\n        }\n        return new ResponseEntity&lt;&gt;(user, HttpStatus.OK); \/\/ Returns 200 with user data\n    }\n}<\/code><\/pre>\n\n\n\n<p><strong>Explanation:<\/strong><\/p>\n\n\n\n<ul><li><code>ResponseEntity&lt;User&gt;<\/code>: Specifies that the response will contain a <code>User<\/code> object.<\/li><li><code>new ResponseEntity&lt;&gt;(HttpStatus.NOT_FOUND)<\/code>: Returns a 404 status code if the user is not found.<\/li><li><code>new ResponseEntity&lt;&gt;(user, HttpStatus.OK)<\/code>: Returns a 200 status code along with the user data.<\/li><\/ul>\n\n\n\n<h4>8. Spring Boot Actuator<\/h4>\n\n\n\n<p><strong>What is it?<\/strong><br>Spring Boot Actuator provides features for monitoring and managing Spring Boot applications.<\/p>\n\n\n\n<p><strong>What does it do?<\/strong><br>It exposes endpoints to retrieve application metrics, health checks, and configuration information.<\/p>\n\n\n\n<h4>Example<\/h4>\n\n\n\n<p>To use Actuator, add the dependency in <code>pom.xml<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;dependency&gt;\n    &lt;groupId&gt;org.springframework.boot&lt;\/groupId&gt;\n    &lt;artifactId&gt;spring-boot-starter-actuator&lt;\/artifactId&gt;\n&lt;\/dependency&gt;<\/code><\/pre>\n\n\n\n<p>You can then access the health endpoint:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>GET \/actuator\/health<\/code><\/pre>\n\n\n\n<p><strong>Explanation:<\/strong><\/p>\n\n\n\n<ul><li>The health endpoint returns the status of the application (e.g., UP or DOWN), giving insights into the application&#8217;s current state.<\/li><\/ul>\n\n\n\n<h4>9. Spring Security<\/h4>\n\n\n\n<p><strong>Basic Concepts:<\/strong><\/p>\n\n\n\n<ul><li><strong>Authentication<\/strong>: Verifying the identity of a user.<\/li><li><strong>Authorization<\/strong>: Checking if an authenticated user is permitted to perform a certain action.<\/li><li><strong>Principal<\/strong>: The user accessing the application.<\/li><li><strong>Credential<\/strong>: Information used for authentication (e.g., password).<\/li><li><strong>Authorities (Roles and Permissions)<\/strong>: Defines what actions a user can perform.<\/li><\/ul>\n\n\n\n<h4>Example<\/h4>\n\n\n\n<p>To configure Spring Security, add the dependency:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;dependency&gt;\n    &lt;groupId&gt;org.springframework.boot&lt;\/groupId&gt;\n    &lt;artifactId&gt;spring-boot-starter-security&lt;\/artifactId&gt;\n&lt;\/dependency&gt;<\/code><\/pre>\n\n\n\n<p>Create a security configuration:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import org.springframework.context.annotation.Configuration;\nimport org.springframework.security.config.annotation.web.builders.HttpSecurity;\nimport org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;\nimport org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;\n\n@Configuration\n@EnableWebSecurity\npublic class SecurityConfig extends WebSecurityConfigurerAdapter {\n    @Override\n    protected void configure(HttpSecurity http) throws Exception {\n        http.authorizeRequests()\n            .antMatchers(\"\/api\/public\").permitAll() \/\/ Allows public access to this endpoint\n            .anyRequest().authenticated() \/\/ All other requests require authentication\n            .and()\n            .formLogin(); \/\/ Enables form-based login\n    }\n}<\/code><\/pre>\n\n\n\n<p><strong>Explanation:<\/strong><\/p>\n\n\n\n<ul><li><code>@EnableWebSecurity<\/code>: Enables Spring Security\u2019s web security support.<\/li><li><code>http.authorizeRequests()<\/code>: Configures URL-based authorization.<\/li><li><code>antMatchers(\"\/api\/public\").permitAll()<\/code>: Allows unauthenticated access to the specified endpoint.<\/li><li><code>anyRequest().authenticated()<\/code>: Requires authentication for all other requests.<\/li><li><code>formLogin()<\/code>: Enables a default login form for user authentication. (By convention, the default username is set to &#8220;user,&#8221; while the password is automatically generated during the project build process and displayed in the console.)<\/li><\/ul>\n\n\n\n<h5>Conclusion<\/h5>\n\n\n\n<p>This tutorial provides an introduction to key concepts in Spring Boot, including reactive programming with Project Reactor, REST controllers, ResponseEntity, Spring Boot Actuator, and Spring Security. <\/p>\n","protected":false},"excerpt":{"rendered":"<p>Spring Boot has revolutionized the way developers build Java applications by providing a framework that simplifies the setup, configuration, and deployment of Spring applications. With its convention-over-configuration approach, Spring Boot allows developers to focus on writing code rather than dealing with complex configurations. In this tutorial, we will explore key concepts and features of Spring [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":3403,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[554,868],"tags":[897,899,896,895,898,900],"_links":{"self":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/3420"}],"collection":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/comments?post=3420"}],"version-history":[{"count":4,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/3420\/revisions"}],"predecessor-version":[{"id":3430,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/3420\/revisions\/3430"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/media\/3403"}],"wp:attachment":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/media?parent=3420"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/categories?post=3420"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/tags?post=3420"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}