June 21, 2022

Spring Boot Application Using Spring Initializr

In this tutorial we’ll see how to create your first Spring Boot application using Spring Initializr (https://start.spring.io/)

Spring Initializr

Spring Initializr provides a quick way to create your own Spring Boot-based project. It provides a Web UI to fill project related details and bootstraps your Spring Boot application. Once you have filled all the details you can download either a generated build file, or a bundled up project as a zip file.

Options you can choose using Spring Initializr are-

  1. Build System- Maven or Gradle
  2. Language- Java, Kotlin or Groovy
  3. Spring Boot version
  4. Project metadata (Group and Artifact), Name, Java version, packaging (Jar or War)
  5. Dependencies- This is the best part where you can select the required dependencies in the form of starters.
Spring initialzr

Spring Boot application using Spring Initializr

For creating a Spring Boot application using Spring Initializr go to https://start.spring.io/ and fill in the required details.

For Spring Boot Hello World web application example details chosen are as follows-

  • Project– Maven Project (another option is Gradle)
  • Language- Java
  • Spring Boot– Version selected is 2.1.6
  • Project Metadata– Group as – com.knpcode
  • Artifact- SpringBootProject

Clicking the Options down button you can provide-

  • Name (prefilled as SpringBootProject)
  • Package (pre filled as com.knpcode.SpringBootProject)
  • Packaging- Jar is selected (War is another option)
  • Java version- Select as per your requirement. Spring Boot 2 requires Java 8 as minimum supported version.

Dependencies– Type web, in the suggested options select Spring Web Starter for the web application. This starter adds the necessary dependencies required for creating a Spring web application, includes Tomcat as the default embedded container.

Click on "Generate the project" and save the generated zip file in your system. This zip file contains the generated Maven project based on the options you chose in Spring Initialzr.

Spring Boot Spring Initializr

Importing generated Maven project

You can import generated Maven project to Eclipse IDE.

Go to File – Import – Maven – Existing Maven Project

In the Root directory select the location where you have unzipped the downloaded zipped project structure. Select the pom.xml file for the project.

Import Maven Project

To have a look at the build file, open pom.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.6.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>
  <groupId>com.knpcode</groupId>
  <artifactId>SpringBootProject</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringBootProject</name>
  <description>Demo project for Spring Boot</description>

  <properties>
    <java.version>12</java.version>
  </properties>

  <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>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>

</project>

First starter that is added in the parent section of the POM is a special starter spring-boot-starter-parent that provides useful Maven defaults. This parent starter also provides a dependency-management section so that you don't need to provide version tags for dependencies.

Each release of Spring Boot provides a curated list of dependencies that it supports. You don't need to provide version for any of these dependencies in your build configuration, as Spring Boot manages that for you. Note that You can still specify a version and override Spring Boot’s recommendations if you need to do so.

In our configuration, Spring Boot version is 2.1.6 so Spring Boot gets the dependencies which support this version.

Since we are developing a web application, we add a spring-boot-starter-web dependency, that adds the necessary dependencies required for creating a Spring web application.

spring-boot-starter-test pulls all the required dependencies for unit testing like Spring Boot Test, JSONPath, JUnit, AssertJ, Mockito, Spring Test.

You will also see a plugin spring-boot-maven-plugin added to your pom.xml. This plugin provides many convenient features-

  • It helps to create an executable jar (über-jar), which makes it more convenient to execute and transport your service.
  • It also searches for the public static void main() method to flag the class having this method as a runnable class.

With these dependencies added Spring Boot takes care of getting the required jar dependencies, even an embedded web server (Tomcat in this case) because of the starter web dependency.

Classes for web application

Maven compiles sources from src/main/java so you will find that structure is created and there is already a generated application class (SpringBootProjectApplication.java) too.

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

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

@SpringBootApplication is a convenience annotation that adds all of the following annotations-

  • @Configuration annotation tags the class as a source of bean definitions for the application context.
  • @EnableAutoConfiguration tells Spring Boot to enable auto configuration so that beans are created automatically based on classpath settings, other beans, and various property settings. For example starter spring-boot-starter-web adds Tomcat and Spring MVC so the auto-configuration assumes that you are developing a web application and sets up Spring accordingly which includes setting up a DispatcherServlet.
  • @ComponentScan tells Spring to look recursively for other components, configurations and services inside this package and register them.

The main method is the application entry point which delegates to Spring Boot’s SpringApplication class by calling run. SpringApplication bootstraps this application, starting Spring, which, in turn, starts the embedded Tomcat web server. You need to pass SpringBootProjectApplication.class as an argument to the run method to tell SpringApplication which is the primary Spring component.

Above Application class in itself gives you an operational web application which on executing initializes the Spring WebApplicationContext and also initializes the embedded Tomcat server.

We’ll add one Rest Controller to demonstrate this web application.

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloWorldController {
  @GetMapping(value="/{name}")
  public String showGreeting(@PathVariable("name") String name) {
    return "Hello " + name;
  }
}

Class is annotated using @RestController annotation which tells Spring that this class is ready for use by Spring MVC to handle web requests and it indicates that resulting string should be written directly into the response body, we don't want to render views.

At method level @GetMapping annotation is used which is short cut for @RequestMapping(method = RequestMethod.GET). This annotation provides routing information. It tells Spring that any HTTP request with the /{name) path should be mapped to the showGreeting method.

@PathVariable annotation lets you retrieve the parameter from the request path.

Running the application

You can run this Spring Boot Hello World application as a stand alone Java application or create an executable jar.

1- You can run it as a stand alone Java application by running the class with the main method (FirstSpringBootApp.java) from Eclipse IDE itself.

Right click SpringBootProjectApplication.java – Run As – Java Application

In the console you will see messages similar to as follows-

2019-07-28 17:50:32.937  INFO 6712 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-07-28 17:50:33.212  INFO 6712 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-07-28 17:50:33.214  INFO 6712 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.21]
2019-07-28 17:50:33.998  INFO 6712 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-07-28 17:50:33.999  INFO 6712 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 5318 ms
2019-07-28 17:50:35.271  INFO 6712 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-07-28 17:50:35.941  INFO 6712 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-07-28 17:50:35.951  INFO 6712 --- [           main] c.k.S.SpringBootProjectApplication       : Started SpringBootProjectApplication in 9.125 seconds (JVM running for 11.574)

You can access the web application by opening browser and giving URL as- http://localhost:8080/knpCode

Here /knpCode is the value for the name parameter.

2- Creating executable- For creating a completely self-contained executable jar file run mvn package from the command line. Once the jar file is created you can run it using following command.

java -jar target\SpringBootProject-0.0.1-SNAPSHOT.jar

Again you can access the web application by opening browser and giving URL as- http://localhost:8080/knpCode

That's all for the topic Spring Boot Application Using Spring Initializr. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment