Skip to main content

Spring BOOT

Spring BOOT: Spring Boot is an open-source Java-based framework used to create a Micro Service.It explores major features of Spring Boot such as 
  • Starters, 
  • Auto-configuration, 
  • Beans, 
  • Actuator and more


Spring Boot provides a good platform for Java developers to develop a stand-alone and production-grade spring application that you can just run

Advantages

Spring Boot offers the following advantages to its developers −

  • Easy to understand and develop spring applications
  • Increases productivity
  • Reduces the development time

Goals

Spring Boot is designed with the following goals −

  • To avoid complex XML configuration in Spring
  • To develop a production ready Spring applications in an easier way
  • To reduce the development time and run the application independently
  • Offer an easier way of getting started with the application
Starters
spring-boot-starter-actuator : monitor and manage your application.
spring-boot-starter-data-jpa : Spring and JPA for database access
spring-boot-starter-security : monitor and manage your application.
spring-boot-starter-web : is used to write a Rest Endpoints
spring-boot-starter-actuator : monitor and manage your application.
spring-boot-starter-thymeleaf : to create web application
spring-boot-starter-test : monitor and manage your application.
spring-boot-starter-web : Spring and JPA for database access
spring-boot-starter-parent
Annotations

@SpringBootApplication : @EnableAutoConfiguration + @ComponentScan
@EnableAutoconfiguration : Automatically configures application based on the dependencies  
 @ComponentScan :scans all the beans and package declarations when the application initializes


Spring Initializer


 CommandLineRunner and ApplicationRunner, to run specific pieces of code when an application is fully started. These interfaces get called just before run() once SpringApplication completes.

When you want to execute some piece of code exactly before the application startup completes, you can use it then. In one of our projects, we used these to source data from other microservices via service discovery, which was registered in Consul.

Ordering

You can register as many application/command line runners as you want. You just need to register them as Beans in the application context. Then, Spring will automatically pick them up. You can order them as well either by extending interface org.springframework.core.Ordered or via the @Order annotation.



Both of them provides the same functionality and the only difference between CommandLineRunner and ApplicationRunner is CommandLineRunner.run() accepts String array[] whereas ApplicationRunner.run() accepts ApplicationArguments as argument. you can find more information with example here

_____________________________________________________________________________________
application.properties


Command Line Properties


@Value("${property_key_name}")

@Value("${spring.application.name:demoservice}")
SPRING RESTFUL DEPENDENCIES
   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
   </dependencies>
           <artifactId>spring-boot-maven-plugin</artifactId>
@RestController : It serves JSON, XML and custom response.

@RequestMapping : Annotation is used to define the Request URI to access the REST Endpoints. 

@RequestBody annotation is used to define the request body content type.

ResponseEntity<Object>
@PathVariable annotation is used to define the custom or dynamic request URI. 

 ResponseEntity<Object> updateProduct(@PathVariable("id") String id)

 @RequestParam annotation is used to read the request parameters from the Request URL.

GET API 

 return new ResponseEntity<>(productRepo.values(), HttpStatus.OK);
@RequestParam(value = "name", required = false, defaultValue = "honey") String name)
POST API
new ResponseEntity<>(productRepo.values(), HttpStatus.OK);

PUT API 
  return new ResponseEntity<>("Product is updated successsfully", HttpStatus.OK);
DELETE API
return new ResponseEntity<>("Product is deleted successsfully", HttpStatus.OK);
@ControllerAdvice 
The @ControllerAdvice is an annotation, to handle the exceptions globally

@ExceptionHandler

package com.tutorialspoint.demo.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class ProductExceptionController {
   @ExceptionHandler(value = ProductNotfoundException.class)
   public ResponseEntity<Object> exception(ProductNotfoundException exception) {
      return new ResponseEntity<>("Product not found", HttpStatus.NOT_FOUND);
   }
}




ResponseEntity.ok("Hello World!");
new ResponseEntity<>(
      "Custom header set", headers, HttpStatus.OK)


  return ResponseEntity.ok()
        .header("Custom-Header", "foo")
        .body("Custom header set");



2
3
4
5
6
@PostMapping(value = "/content", produces = MediaType.APPLICATION_JSON_VALUE)

@PostMapping(value = "/content", produces = MediaType.APPLICATION_XML_VALUE)


RestTemplate





For monitoring and managing your microservice application via Spring Boot Admin Server, you should add the Spring Boot Admin starter client dependency and point out the Admin Server URI into the application properties file.

Note − For monitoring an application, you should enable the Spring Boot Actuator Endpoints for your Microservice application.

First, add the following Spring Boot Admin starter client dependency and Spring Boot starter actuator dependency in your build configuration file.




Cross-Origin Resource Sharing (CORS) is a security concept that allows restricting the resources implemented in web browsers. It prevents the JavaScript code producing or consuming the requests against different origin.






Comments

Popular posts from this blog

Microservices Design patterns

What are microservices? Microservices - also known as the microservice architecture - is an architectural style that structures an application as a collection of services that are Highly maintainable and testable Loosely coupled Independently deployable Organized around business capabilities Owned by a small team The microservice architecture enables the rapid, frequent and reliable delivery of large, complex applications. It also enables an organization to evolve its technology stack. You are developing a server-side enterprise application. It must support a variety of different clients including desktop browsers, mobile browsers and native mobile applications. The application might also expose an API for 3rd parties to consume. It might also integrate with other applications via either web services or a message broker. The application handles requests (HTTP requests and messages) by executing business logic; accessing a database; exchanging messages with other systems; and returni...

GraphQL

What is GraphQL  API Standard invented & open-sourced by Facebook Alternative to  REST API  enables declarative data fetching  exposes single endpoint & responds to queries How it works?  Why Graphql? Improvises performance by reducing the data that is to be transferred over the internet Variety of different frontend frameworks and platforms on client-side Fast development speed & expectation for rapid feature development Why Graphql is better than REST? Flexibility & efficient  No more over /under fetching of data Over fetching : Under fetching: Insightful analytics  Schema serves as contract between client and server CORE CONCEPTS : SDL :SCHEMA DEFINITION LANGUAGE Writing Data with mutations 3 kinds of mutations creating new data updating existing data deleting existing data

Jackson

<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId> jackson-core </artifactId> <version>2.9.6</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId> jackson-annotations </artifactId> <version>2.9.6</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId> jackson-databind </artifactId> <version>2.9.6</version> </dependency> CBOR encoded data with Jackson <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-cbor</artifactId> <version>2.9.6</version> </dependency> In order to read and write MessagePack encoded data <dependency> <groupId>org.msgpack</groupId> <artifactId>jackson-dataformat-msgp...