Skip to main content

Fundamentals Of Spring Boot


Spring boot is becoming very popular now a days for creating web application ,commonly used for creating microservice based architecture.In this blog post, you will know the fundamental of spring boot and how to use spring boot in real world project. The idea here is not just to go through theory part but to have clear understanding of spring boot with doing practice.Here we are going to create a full fledge web application using spring boot.


As we proceed through this course we will be covering below topic-
  • Spring Boot Starters
  • Containerless Deployments
  • Auto-configuration
  • Testing with Spring Boot

Prerequisite

This course has been developed by keeping in mind that the audience have prior knowledge of basic of Java and Spring fundamentals.
  • Java 1.8+
  • Gradle or Maven
  • IDE (Spring STS ,Eclipse etc.)

Creating your first spring boot project

Welcome to the course of creating your first spring boot application. Spring boot is a very large topic and combine with spring.This course will cover the fundamental of working with spring boot and creating a web application. This course is gear towards beginner and intermediate spring developer to introduce spring boot in that context ,giving you an understanding of what it is , how to use it and cover the fundamental concept of architecture of the framework.

This platform is a game changer for java application.If you never had a chance to use spring boot before get ready for paradigm shift and how you think about building web application with Java technology. Just to show how great spring boot is ,we will be building a spring boot application from scratch.

Spring boot can be created by using Maven and Gradle ,In this course we will be using Maven build tool to create a simple web application. In this course we are going to create a promo-api ,it will have simple crud operation like posting a new promotion, updating a promotion, getting list of promotion and deleting a particular promotion.

So let's start - Open up STS if you don't have it you can download from Here,Go to new -> Maven -> maven project->next->finish. Once done below folder structure will look like-

Now to make this application works as spring boot,we have to add parent to our Maven project. It is used to declare that our project is a child to this parent project.
After that add the following dependency to the pom.xml file. Here, we are adding web dependency by adding spring-boot-starter-web.
After that add Java version for the project.
<properties> <java.version>1.8</java.version> </properties>
Now save it will download all the dependency of spring framework. After saving if you navigate to the problems tab you will see below error-
To resolve this go to project folder, right click ->maven -> update project .In the left hand in maven dependency you can see that maven has downloaded all the dependent jar file to it's classpath. Now we are going to create a simple java application to run as a spring boot application. To create a spring boot application you have to to do two things ,first you have to annotate your class with @SpringBootApplication and inside the main method add SpringApplication.run(app.class, args) ,I will explain this in details later on. When class is annotated with @SpringBootApplication ,it does below things -
  • Sets up default configuration
  • Starts spring application context
  • Performs classpath scan
  • Starts tomcat server
To run the spring boot application go to main class right click ->run as -> Java Application ..boom that's pretty simple .It will start your application in localhost at port 8080.
Now as server has started let's create some restcontroller ,create a new package and inside that create a new controller class.
After doing that restart your server and in your favorite brower hit "http://localhost:8080/promo/" .This is all needed to start a spring boot application.We will create the entire application but before that let see what controller class is doing here. The controller class is annotated with @RestController and @RequestMapping ,this helps to create a controller and map the path to given value in request mapping.I have created a simple method in a controller annotated with @RequestMapping to map the path of the method which return string as output.

BOM :Bill of Materials

Spring boot makes life easier when we need to integrate different library in a framework and the spring boot call it a BOM stands for bill of materials.Instead of adding all dependency separately with version spring boot comes with parent dependency management. By including,
Spring boot manages all the transitive dependency with version.It saves us an extra effort to manage version of all dependency.

Others Spring Boot Initializers

Even if rolling up spring boot application is not that hard ,still spring boot provides with extra tools to create a spring boot application
Spring initializer is web tools that spring provide ,and you can create entire spring application with different dependency.I suggest you to go to start.spring.io and try creating spring boot project.Here spring boot has covered almost all dependency needed to create a web application. The other way of creating an spring boot application is through command line(Cli) ,internally spring boot calls the same web api to create an app.As many developers are interested in working with command line it may attract them as well.You can follow below docs to create spring boot using command line.
Spring boot also provides some sample projects in spring git hub repository ,please use the below url to get to sample project.

How Does Spring Boot Works ?

Now let's dive deeper into how spring boot works internally.As we know spring boot is a java application so for any java application to run JVM needs a public static main(String [] args) method.This method will fire up spring boot but wait a second how it does ?
Spring boot has tomcat as embedded sever and bunch of internal configuration that helps spring boot to run .We will go step by step to dive deeply into it. When main class runs it will first starts java then the application ,at top level we have @SpringBootApplication annotation, it has bunch of internal auto configuration primarily for spring boot.
@SpringBootApplication : A convenience annotation that wraps commonly used annotation with spring boot.The annotation is equivalent to using @Configuration, @EnableAutoConfiguration and @ComponentScan with their default attributes.
@Configuration : This is spring configuration on start up, here in spring boot we don't use any xml for configuration. This annotation is best suited for creating configuration in Java class itself.It allows to register extra beans in the context or import additional configuration classes.
@EnableAutoConfiguration : Spring Boot auto-configuration attempts to automatically configure your Spring application based on the jar dependencies that you have added.Enable auto-configuration of the Spring Application Context, attempting to guess and configure beans that you are likely to need. Auto-configuration classes are usually applied based on your classpath and what beans you have defined.Auto-configuration tries to be as intelligent as possible and will back-away as you define more of your own configuration. You can always manually exclude() any configuration that you never want to apply. Auto-configuration is always applied after user-defined beans have been registered.
@ComponentScan : This will scan the project for spring components.Spring can auto scan, detect, and instantiate components from pre-defined project packages. Spring can auto scan all classes annotated with the stereotype annotations @Component, @Controller, @Service, and @Repository.

Why Move to Containerless Deployments

When an application is deploy inside a container there are lot of pre-set up configuration which is needed to be done.If you have production ,dev and stage environment the container needs to be set up in each places. You will have to set up deployment descriptor web.xml to tell container the working flow of your application.In case if container is embedded into your application it gives to privilege to run your application anywhere without any pre set up configuration and application will tell the container to respond on http request. Below are major difference between them-
Now that we have come this far and got to know how spring boot framework works and also created a simple spring boot web application.Spring boot auto configure spring mvc patterns for us.We will go to create full functional spring boot app by creating some more controller, services and data model.

Restful Web App

There are lot of ways that you can built user interface for an application these days.let's go ahead and pick one ways to accomplished that in this course.
As spring boot inbuilt with spring core ,spring mvc and spring rest .In the diagram above showed how typical web application looks like.Client makes http/https request to server to do some job. A client can be any web browser or a front end application who will utilize the rest controller and ask server to do a task.

Integrating Front End Part in Spring Boot

I am not going to cover front end part of application but I can brief about how spring boot used for integrating front front end part is spring boot application.In spring boot you can build front end client assets by including public or static folder in classpath.
Please follow below steps to integrate front code with spring boot -
1. Create a resources folder inside src/main directory ,by default anything including into this folder can be taken on classpath in spring boot.
2. Create public or static folder inside src/main/resources folder
3. Create index.html file and put it into src/main/resources/static folder and update the maven project.Any client code can be put into this folder will be taken as part of classpath.

Spring MVC Rest Controller

We have done the enough of theory ,now get our hand dirty by extending our working spring boot application.We are going to perform basic CRUD operation inside the RestController-
We are going to create following rest Uri for all the CRUD operation -
1. GET promo/get (get the list)
2. POST promo/add (add)
3. PUT promo/update/{Id} (update)
4. DELETE promo/delete/{Id} (update)
Update your controller class with below code added-
Create a model class -
Create a repository for performing all the CRUD operation -

That's it !!! You got it now ,we have fully functional spring boot rest controller.You can hit "http://localhost:8080/promo/get" in postman to see our app in working fine. We will add the external database later on until then simple java class is handling all operation.

Spring MVC Integration Overview

At this point we have successfully created spring boot rest apis.let's take a moment and talk about what spring boot did to auto-configure and integrate spring MVC for us. When we added the spring-boot-started-web dependency in pom.xml ,spring boot did more than simple adding jar file to the class path.As we already have auto-configuration enable in @SpringBootApplication annotation ,spring doest some extra steps to set up spring MVC feature for us.Firstly it sets up view resolver automatically.In our case spring boot told spring MVC to set up content negotiating resolver which determine how to respond based on content type. Spring boot also sets up Jackson Json library to handle content type.Next spring boot configure spring MVC to server static content rooted in the classpath under public or static folder.In the end sets up HttpMessageConverter to convert Json into Java object and vice versa.

Properties and Environment Configuration

So far everything we have done with spring boot using the default set up and auto-configure what framework provide for us.What is we want to change something in out application to behave differently than default behavior.Spring boot provides us application.properties where we can set a bunch of configuration with key and value pairs. When the spring boot starts up it sets up all the properties available inside application.properties file.The best way to put this file again into src/main/resources directory. We can also have multiple application properties file for different environment.
We can create application-{profiles}.properties for different environment like dev and stage.Eg.(application-dev.properties for dev environment).
I am going to set up a basic environment properties in our application by creating application.properties file. As spring boot provides ton of properties you can navigate through https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html link for having more information about properties.
By setting server.port property to 8181 ,spring boot will start up tomcat to port 8181.
I have covered Spring boot in multiple post, hence kindly follow below order to learn completely-

Comments

Popular posts from this blog

Spring Data JPA and @Query Annotation

As in the last post on query DSL, I have discussed about creating various custom finder methods to query in database. You also know that spring data JPA internally form JPQL to query in database. In this module I am going to cover query annotations that spring data JPA provides with some advanced features. @Query annotation In order to define SQL to execute for a Spring Data repository method, we can annotate the method with the @Query annotation — its value attribute contains the JPQL or SQL to execute. In the custom JPA repository we can define multiple query DSL methods to query data from database for different condition. Consider a case where condition being passed in the query are too many. Though you can form custom finder method but the method is going to be very large and cumbersome. In such type of scenario the best way is to write simple method and use @Query annotation on top of method. When the @query annotation is being used spring data JPA ignores the structure of f

Query DSL Overview

This post is the continuation of my previous post on spring data JPA. In this post I would be delving deeply into query DSL.Query DSL is an advanced feature provided by spring data JPA to query data from database. It has less code so less to maintain.By using query DSL one can check query at start up rather than at runtime. I am going to discuss key and concepts require to learn DSL and would learn through example. We will extending the same promo-api that we wrote in last post and would be writing Junit to verify query. DSL stands for a domain specific language and is a customized extension of a software programming language that addresses a specific business or domain. In case of spring data JPA this means the framework is enhancing Java to be better suited for creating and working with JPA query. The spring data JPA query DSL is simply all about finding terms and syntax to work with JPA query more efficiently. To demonstrate how query DSL works ,let us take an example to explain

Spring Data JPA Paging, Sorting, Custom Repository, Auditing and Locking

In this module we will talk about some of advance features that spring data JPA support for developing an enterprise application. They are paging and sorting ,auditing, locking and custom repository. Paging and Sorting As a web application developer if you have to display thousands of records on the UI it is not a good practice to just query database and display it to UI. Spring data JPA provides paging and sorting mechanism to handle such type of scenario. These are most sought problem if you are dealing with a big enterprise application, keeping this into mind spring data JPA has provided in built support for paging and sorting. You can see above that spring data JPA has PagingAndSortingRepository interface and it has findAll method. Sort and Pageable object are getting passed as part of findAll() method parameters. What do you think Pageable does behind the scene. Basically Pageable is an interface and when spring data JPA fetch value from database it limits the result. So inte