Skip to main content

Learn SpringBoot

 What is SpringBoot?

               SpringBoot is one of the Java Spring Framework. Using  SpringBoot developers can develop web applications, Rest API for use on any frontend side, and do many things. 

Why use SpringBoot?

  • Provide Autoconfiguration (No need for XML configuration.)
  • Reduce development time. 
  • Creates stand-alone spring applications.
  • Fast and easy development.
  • Reduce the amount of source code.
  • Simple setup and management.
  • Directly embedded with servers like Tomcat, Jetty, Undertow, etc...
Limitations of SpringBoot:

  • Complexity
  • Limited control of your application
How to create a SpringBoot project?

Spring Boot Initializer

  1. Go to https://start.spring.io/
  2. Select the project which you want to create ( Maven/Gradle)
  3. Select language (Java/Kotlin/Groovy)
  4. Select the Spring Boot version
  5. Fill in Project metadata
  6. Add at least basic starter dependencies of spring boot

Meaning of spring boot versions:

SNAPSHOT: 
It means that the version has not been released. Every day their new build will be replaced by the previous build.

M#:
Once a development milestone was reached a single build is made that is called M#. For the next milestone # is increased by one. Milestones are never overwritten.

GA: 
It means that the version has been released and will not change in this version. 

Some basic starter dependencies :

Maven/Gradle:

Name

Description

spring-boot-starter-data-jpa

Starter for using Spring Data JPA with Hibernate

spring-boot-starter-web

Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container.

spring-boot-starter-thymeleaf

Starter for building MVC web applications using Thymeleaf views like HTML etc…

spring-boot-starter-security

Starter for using Spring Security

spring-boot-starter-test

Starter for testing Spring Boot applications with libraries including JUnit Jupiter, Hamcrest, and Mockito

spring-boot-starter-tomcat

Starter for using Tomcat as the embedded servlet container. Default servlet container starter used by spring-boot-starter-web

spring-boot-starter-actuator

Starter for using Spring Boot’s Actuator which provides production-ready features to help you monitor and manage your application

spring-boot-starter-json

Starter for reading and writing json

spring-boot-starter-mail

Starter for using Java Mail and Spring Framework’s email sending support

             
Annotations:   

        Many annotations are used to develop projects faster and easier. Below are some useful annotations that are used in spring-boot projects.

@SpringBootApplication:

              It is used to run the spring boot application. It is a combination of  three annotations:
        @Configuration,@ComponentScan,@EnableAutoConfiguration  

@Configuration:

            It is used when the class has @Bean definition methods. Spring containers can process the class and generate their required bean for spring boot applications.  

@ComponentScan:

            It enables component scanning in spring. It is asking spring to detect spring-managed components. It is used with @Configuration annotation.

@EnableAutoConfiguration:

            It enables spring boot to auto-configure the application context. By using this annotation spring automatically register and create their beans which are included in jar files, classpath, and defined by us.

@Bean:

            It is applied to the method. It is specified that it returns a bean that is need to be managed by spring context. It is usually declared in configuration classes' methods.

@ConditionalOnBean: 

            By using of this you can add a condition to specific @Bean methods. If the condition is satisfied then only that bean will be added to the application context.

@Autowired:

            It is used for automatic dependency injection. By using this annotation, we can access methods of specific classes.

@Controller: 

               It is applied to the class. It is used to make websites. It is intermediate between business logic and view. Their method returns a string, HTML, or JSP file that indicates which route to redirect. Mostly used with Request mapping annotations like @RequestMapping,@GetMapping,@PostMapping, etc...

@RestController: 

          It is applied to the class. It is used to make the rest APIs. It is a combination of @Controller and @ResponseBody annotations. Mostly it returns ResponseEntity. it needs to be applied @ResponseBody annotation in this classes' methods for returning specific data to other apps or servers.

@Service: 

                It is applied to the class. It contains business logic. We can apply that service's logic to the controller or the rest controller classes.

@Repository: 

                It is applied to the class and interface. It is used to access the database directly and perform all operations related to the database. In this, we can make HQL queries.

@Value: 

                It is used to get the value of the application.properties file. It is used to assign the default value of variables and the method's arguments.

@RequestMapping:

                It is used to map the web requests like GET, POST, etc... It has many optional elements like consumes, header, method, name, params, path, produces, and value.

@PropertySource:

                It is used with @Configuration classes. It provides properties file to the spring environment.

@Profile:

                It allows registering beans by condition. It contains several values like dev, prod, live, local, etc... For that, we need to make multiple application.properties files like application-dev.properties, application-prod.properties, etc… and by that, we can override our content. 

@Import: 

               It indicates one or more @Configuration classes to import. It is declared at class-level or meta-level. It works great when we need to register not all but some of the components from a package.

@PathVariable:

                It is used to extract the values from the URL. It is most suitable for restful service, where the URL contains a path variable. We can define multiple @PathVariable in a method.

For example: 

        URL -> http://localhost:8080/user/1

        here "1" is the path variable.

@RequestParam:

                It is used to extract the query parameters from the URL. It is most suitable for web applications. We can specify the default value if the query parameter is not present in the URL.

For example:

    URL -> http://localhost:8080/user?id=1

        here "id" is the query parameter.

@ModelAttribute:

                It is used to inject data objects in the model before JSP loads and read data from an existing model. It is applied in the method. It cannot be mapped directly to any request.

@RequestBody:

                It allows us to retrieve the request's body and automatically convert it to a Java object. We use this annotation as a method parameter.

@ResponseBody:

                It can be put on method and as a return type of method. It tells spring boot to serialize an object into JSON or XML.


@RequestHeader:

                It is used to get information about HTTP request headers. We use this annotation as a method parameter. It has many optional elements like name, value, required, and defaultValue. We can use it multiple times in the method parameter.

@ResponseHeader:

                It represents a header that can be provided as a part of the response.

@GetMapping:

               It maps the HTTP GET request to the specific method. It is short cut for @RequestMapping(method = RequestMethod.GET). It is used to fetch records of some web services.

@PostMapping:

               It maps the HTTP POST request to the specific method. It is short cut for @RequestMapping(Method = RequestMethod.POST). It is used to create or insert data in the web services endpoint.

@Required:  

                It applies to the bean setter method. It is method-level annotation. It can be used to mark a property as 'Required-to-be-set'. It indicates that the affected bean property must be populated at configuration time with the required value of property otherwise it throws the 'BeanInitilizationException' exception.

       @Entity:

                It specified that the class is an entity and is mapped to a database table.

      @Table:

                It specified the table in the database. It has four optional attributes: Name, Schema, UniqueConstraints, Catalog, Indexes. 

Name: It is the name of the table.

Schema: It is the Schema of the table.

UniqueContraints: It is used to apply a unique constraint on the table.

Catalog: It is a catalog of the table.

Indexes: It is used to give an index on the table.

      @Id:

            It specifies the primary key of an entity.

      @Column:

            It is used to add or map a column to the table. If no Column annotation is specified, then it is mapped with the field name of the table. It has many optional attributes like Name, length, nullable, Table, Unique, updatable, Precision, insertable, columnDefinition.

      @GeneratedValue:

            It specifies that the value will be automatically generated for that field. It has two attributes 'strategy' and 'generator'. Strategy has four type:

            GenerationType.AUTO

            GenerationType.IDENTITY

            GenerationType.SEQUENCE

            GenerationType.TABLE


        

References: 




Comments

Popular posts from this blog

Simple example of spring boot with maven

In this post, we create a simple spring boot application with Maven. Technology used: Project: Maven project SpringBoot Version: 2.6.5 Java: 8 Editor or IDE: Eclipse How to create Maven Project in Eclipse? First, create a project with a spring boot initializer and unzip in a specific path of file explorer then follow the below steps in eclipse: 1) Go to File Menu. 2) Click on import . 3) Click on Existing Maven Projects . 4) Browse the path of your project which is created by the spring-boot initializer. 5) Click on Finish . How to run the application in Eclipse? First, build and then run an application using the following steps:     Build application: 1) Right Click on your project in Project Explorer. 2) Click on Run As . 3) Click on Run Configurations... 4) Click on Maven Build (In the left panel of opened dialog) 5) Provide a Name of the configuration. 6) Click on Workspace and select your project. 7) Write " clean -X install " in Goals. 8) Click on Apply . 9) Click...