SpringBoot

Last Updated on: February 22, 2021 pm

Spring Initializer

Enter Spring Initializer and generate a new SpringBoot Project.

Import project into IDE.

SpringBoot Solution

  1. Make it easier to get started with Spring development

  2. Minimize the amount of manual configuration

    • Perform auto-configuration based on props file and JAR classpath.
  3. Help to resolve the dependency conflicts (Maven or Gradle)

  4. Provide an embedded HTTP server so you can get started quickly

    • Tomcat, Jetty, Undertow…

SpringBoot Project Structure

Maven Wrapper Files

mvnw allows you to run a Maven Project.

  • No need to have maven installed or present on your path.
  • If correct version of Maven is NOT found on your computer, it will Automatically downloads correct version.

Two files are provided.

  • mvnw.cmd is for Windows - mvnw clean compile test
  • mvnw is for Linux/Mac - ./mvnw clean compile test

Maven POM File

Spring Boot Maven plugin

1
2
3
4
5
6
7
8
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

To package a executable JAR file or create a war archive file.

You can also run the app like this:

1
2
$ ./mvnw package
$ ./mvnw spring-boot:run

Java Source Code

MycoolappApplication.java

1
2
3
4
5
6
7
8
9
10
11
package com.luv2code.springboot.demo.mycoolapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MycoolappApplication {
public static void main(String[] args) {
SpringApplication.run(MycoolappApplication.class, args);
}
}

@SpringBootApplication

It enables

  • Auto configuration
  • Component scanning
  • Additional Configuration

Composed of the following annotations:

  • @EnableAutoConfiguration - Enable Spring Boot auto-configuration support
  • @ComponentScan - Enables component scanning of current package, also recursively scans sub-packages
  • @Configuration - Able to register extra beans with @Bean or import other configuration classes

SpringApplication Class

  • Creates application context and register all beans.
  • Starts the embedded server Tomcat etc…

More on Component Scan

1
2
3
4
@SpringBootApplication(
scanBasePackage={"com.luv2code.springboot.demo.mycoolapp",
"org.acme.iot.utils",
"edu.cmu.wean"})

You need to explicitly list the base packages to scan, if you got other packages.

Resources

Application Properties

You can add Spring Boot properties.
server.port=8585

You can add your own custom properties.

coach.name=Mickey

Read Data from the properties File
1
2
3
4
5
@RestController
public class FunRestController{
@Value("${coach.name}")
private String coachName;
}

Static Content

Examples of static resources HTML, css, JavaScript, Images, etc…

Do not use the /src/main/webapp directory if your application is packaged as a JAR.

Although it is a standard Maven Directory, it works only with WAR packaging.

It is sliently ignored by most build tools if you generate a JAR.

Templates

SpringBoot includes auto-configurations for the following template engines.

  • FreeMarker
  • Thymeleaf
  • Mustache

SpringBoot Starters

A curated list of Maven Dependencies.

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

What is in the Starter?

Starter Parent

1
2
3
4
5
6
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.0-M1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

For the Spring Boot Starters, no need for version.

Basically, only specify the version of Spring Boot Parent.

Then for the actual dependencies, simply inherit version from Starter Parent.

No need to list individual versions, great for maintenance and make sure all the dependencies are compatible.

Benefits of SpringBoot Starter Parent

  • Default Maven configuration: Java version, UTF-encoding etc…

  • Dependency management

    • User version on parent only
  • Default configuration of Boot plugin

Spring Boot Actuator

Exposes endpoints to monitor and manage your application.

Get DevOps functionality out-of-box.

Simply add the dependency to your POM file.

REST endpoints are automatically added to your application.

  • /health - Health information about your application
  • /info - Information about your project

By default, only health and info are exposed.

Applying Security

Add Dependency

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Add Properties in the application.properties file

1
2
3
4
5
6
info.app.name=My Super Cool App
info.app.version=1.0.0
management.endpoints.web.exposure.include=*
spring.security.user.name=d
spring.security.user.password=d
#management.endpoints.web.exposure.exclude=health,info

Running from the Command Line

1
2
3
> ./mvnw package
> cd target
> java -jar jarname.jar

OR

1
> ./mvnw spring-boot:run

JPA

Java Persistence API - JPA

  • Only a specification
  • Defines a set of interfaces
  • Requires an implementation to be usable

Benefits

You are not locked to vendor’s implmentation.

Maintain portable, flexible code by coding to JPA spec(interface).

Spring Data JPA

JPA Repository

Spring Data JPA provides the interface: JpaRepository

  • findAll()
  • findById()
  • Save()
  • deleteById()

Create a JPA Repository Interface

1
2
3
4
5
6
import com.luv2code.springboot.curddemo.entity.Employee;
import org.springframework.data.jpa.repository.JpaRepository;

public interface EmployeeRepository extends JpaRepository<Employee,Integer> {

}

Then you can use the CRUD operations of the interface for free.

Spring Data REST

Create the REST API using the existing JPA repository.

Add new dependency to thepom.xml

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>

Problem

2021-02-17 10:52:52.396 ERROR 27449 — [ main] o.s.b.d.LoggingFailureAnalysisReporter :

* APPLICATION FAILED TO START *

Description: Web server failed to start. Port 8080 was already in use.

Action: Identify and stop the process that’s listening on port 8080 or configure this application to listen on another port.

Solution1

lsof -i:8080 check the process using port 8080.

kill pid kill the process of the id.

Solution2

Do not allow parallel run, otherwise there will be more than one instance running on the same server port.