Spring Boot tutorial – A to Z

  • by

Here in this page, I will be covering most of topics on Spring Boot. If you are already familiar with Spring framework and wanted to learn about Spring boot now, you are welcome. And if you are new to Spring framework itself, then I would recommend you to go through the topics of Spring Core and Spring MVC first before diving into any further topics on this page.

So let’s get things rolling!

Estimated Duration: 20 min

sprin-boot-tutorial

What you will get?

At the end of this page you will be able to run your a working Spring Boot web application on your laptop/desktop/Mac. Read on!

The following are the topics covered in this page alone. Some of the advanced topics may ask you to load another page (link will be provided on those topics text itself for you to navigate) and you can get it covered exclusively and in detailed.

Topics

  1. Why Spring Boot?
  2. Get me to the source Code!
  3. RestController concept
  4. Accessing Data from/to your database
  5. Enable Logging in Spring Boot
  6. Securing web API with Spring Security
  7. Automation projects using Spring Boot
  8. Adding TestNG to Spring Boot
  9. Running Spring Boot in a container
  10. Monitoring Spring Boot app using built-in dependencies
  11. Performance optimization for Spring Boot
  12. How to shrink memory size of Spring Boot app?

Please bookmark this page (CTRL+D) for quick reference in future.

Why Spring Boot?

Simple answer is: Boot gives you wings. If you are an existing Spring application developer then you will get Boot apps in lesser amount of time. Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can “just run”. Don’t worry, you will be going through all these along with this page topics.

Get me to the source Code!

GitHub project “mbase” source project code is available in this link. Clone the repository and modify application.properties file with your own database details in it.

$ git clone https://github.com/naveen92/mbase.git

Once you have cloned the project, navigate to src – main – java  and find for “Application.java” class file. This is the main file which boots the application by the help of an annotation “@SpringBootApplication”. We use the @SpringBootApplication annotation in our Application or Main class to enable a host of features.

@SpringBootApplication
@EntityScan("com.naveen.mbase.entity")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

RestController concept

The project “mbase” which I mentioned above is based on RESTful API model of serving data to the front-end. We use java class which represents an endpoint. We call them REST controller by convention.

Front end html pages requests for data asynchronously and these REST controllers will be serving data to them. You may have already seen such things in your Spring projects. There’s an annotation called “@RestController” which marks a class as a REST controller class.

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.naveen.mbase.entity.Birthday;

@CrossOrigin(origins = "*")
@RestController
public class BirthdayRestServiceController {
	@Autowired
	private IBirthdayRepository repo;

    // CREATE
    @RequestMapping("/birthday/create")
    @ResponseBody
    public String createBirthday(String _name, String _date) {
    	Birthday birthday = new Birthday(_name, _date);
        try {
            repo.save(birthday);
        } catch (Exception e) {
            return e.getMessage();
        }
        return "creation successful: " + String.valueOf(birthday.getId());
    }
     
    // READ
    @RequestMapping("/birthday/read")
    @ResponseBody
    public Birthday readBirthday(long id) {
    	Birthday birthday = null;
        try {
        	birthday = repo.findOne(id);
        } catch (Exception e) {
        }
        return birthday;
    }

    // some more method goes here..

    @RequestMapping("/birthday/readRecent")
    public List<Birthday> readRecent() {
        List<Birthday> __birthday = repo.findAll();
        return __birthday;
    }
}

Public methods inside these REST controllers can be used to serve an API endpoint using a HTTP method. These methods in turn will call application service classes. A class which serves data or does similar processing/services are termed as Service class or Service component in Spring boot. Usually these classes are marked as a “service” by adding an annotation “@Service” as we see the same way as in REST controller.

Accessing Data from/to your database

Spring Boot comes with a framework project which allows us to access data to and from a database. Spring Data’s mission is to provide a familiar and consistent, Spring-based programming model for data access while still retaining the special traits of the underlying data store.

Spring data not only supports RDBMS systems like Oracle DB, MSSQL but also supports any kind of data interaction your application would probably be liking to obtain for functioning. Some of them are Spring Data JDBC, Spring Data JPA, Spring Data LDAP, Spring Data MongoDB, Spring Data Redis and so on.

If you have an RDBMS service serving you data such as an Oracle database or MySQL or MSSQL database, then you would be going after either Spring Data JPA or JDBC module.

To add this module in your maven pom file, add them inside application dependencies list. Navigate to pom.xml file of “mbase” project which I have mentioned in the beginning of this page for more reference and guidance on adding and maintaining list of application Spring Boot specific maven modules.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

Also make sure you provide DB user details along with DB connect string and port number in the application.properties file to help your new spring boot application to access database. Also provide firewall port access to your application server where you will be running this sample Spring boot application.

Enable Logging in Spring Boot

The “mbase” project which you have cloned doesn’t have logging mechanism provided by modules like SL4J. There’s a guide here at Mkyong site. You can also clone his project at https://github.com/mkyong/spring-boot.git by issuing the following command.$ git clone https://github.com/mkyong/spring-boot.git.

Securing web API with Spring Security

When you are done with basic level in developing a Spring Boot application in your desktop, then you are ready to get it deployed to production. And you just need to implement a specific type of security mechanism onto your app to get it secure to the public internet or to your enterprise.

To add security features to your app, you need Spring Security project from Spring framework. Do the following steps to make it working in just 2 minutes.

Add Spring Security project dependency into your pom.xml file.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

Add security configuration in your Application.java class file.

    @EnableWebSecurity
    @Configuration
    class WebSecurityConfig extends WebSecurityConfigurerAdapter {
     
      @Override
      protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
        .antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
        .antMatchers("/evttracker/inc").permitAll()
        .anyRequest().fullyAuthenticated().and().
        //httpBasic().and().
        formLogin().and().
        csrf().disable();
      }
      
    }

Automation projects using Spring Boot

Now you got to know about Spring Boot a lot. Let’s add spice to the application now. If you have an automation work requirement pending on you desk right now, then we can use Spring Batch project to make it possible and complete the entire project at ease using Spring boot.

When you have finished composing the list of tasks that you need to accomplish to make a work done, you can then make them converted into smaller tasklets redefined in such a way to make it easier for you to implement straight using Spring Batch.

Tasklet and Chunk are the two ways to process a step in Spring Batch. This is the first thing you need to remember.

Tasklet

Though not commonly used, Tasklet is a single task that needs to be executed. It is used in case of simple and granular tasks like deleting a resource or executing a query. Also note that aggregation is not involved for tasklet task execution.

Chunk

Now it is clear that chunk is direct opposite to Tasklet. Chunk processing involves complex tasks involving reads, processing and writes the we use chunk oriented processing. Its the most common way of executing a Step. Usually used in scenarios like copying, processing and transferring of data.

Adding TestNG to Spring Boot

TestNG is a good testing framework you can rely up on when you want to add test case execution to your Spring boot application, These cases written in TestNG annotations will gets executed during build time. You can also execute these test cases post build or even can be skipped during application build using maven. The same goes to gradle and other build scripting and build engines.

Read more about Setting up TestNG with Spring here.

Running Spring Boot in a container

World is moving towards containerization. The concept of isolating your application process (in OS level) with other processes (either of OS or of your another services) is termed as containerization of a application service.

You need to do this as part of production deployment of today’s sample application not just because that everyone’s doing.. It is because it makes more sense that instead of considering it as a WAY, now-a-days the enterprises consider it as a new STANDARD.

So how do you do that? So how will I do? I will do it in this way! First I will be installing docker service in my host machine (a prod server). Then I will create a folder and move my executable jar of my project over there. With “docker run” command I will start my container.

There are some key things you need to know if you are running your application in a container.

  1. Your application main thread runs as a process inside the container. If you kill it, then the container stops.
  2. You need to allow inbound and outbound port numbers for your container. This is called as port mapping. Since you have virtualized the container from the OS, you need to map the internal port (app port, note that Spring boot app “mbase” uses embedded tomcat and it exposes a port to access the service API).

Monitoring Spring Boot app using built-in dependencies

Spring Boot Actuator module helps you monitor and manage your Spring Boot application by providing production-ready features like health check-up, auditing, metrics gathering, HTTP tracing etc. You just need to add one more dependency in your pom.xml file.

Performance optimization for Spring Boot

How do you measure your Spring Boot application performance? Answer: Using 3 of them: First is “Average application response time”, second is “Average concurrent users must the system support” and third is “Expected requests per second during peak load”.

Any request from WWW will hit your server and one of thread from server thread pool will respond to the request. This is high level. In low level, that responding thread will create more stack calls internally. And it is worst if you use a very big framework like Spring.

You need to avoid bottleneck situations in accessing various levels of your web app stack. Identifying them itself if tedious but not impossible. This can be achieved by writing “Load test cases” which will execute and try to burn the service by issuing pseudo load from within inside of your app. Learn more at  https://stackify.com/java-performance/

How to shrink memory size of Spring Boot app?

The effect Spring Boot on its own has on a Java application is to use a bit more heap and non-heap memory, mostly because of extra classes it has to load. The difference can be quantified as roughly an extra 2MB heap and 12MB non-heap.

You can learn more about it here – https://spring.io/blog/2015/12/10/spring-boot-memory-performance

How useful was this post?

Click on a star to rate it!

Average rating 3 / 5. Vote count: 1

We are sorry that this post was not useful for you!

Let us improve this post!

Leave a Reply

Welcome to CloudiKnow.com blog, a platform to share knowledge and solution experience related to public cloud is base design of this site.

You can start the cloud journey right from here!
Please bookmark this page by pressing simply CTRL+D.