Wednesday, September 21, 2022

Spring Boot Spring Initializr

In the post Spring Boot Hello World Web Application Example we have already seen how to create a Spring Boot application by adding Maven dependencies yourself but you don’t even need to add dependencies or create build file yourself instead you can use Spring Initializr to create a Spring Boot application.


Using Spring Initializr

Spring Initializr provides a web UI (https://start.spring.io), you can enter details about your application, pick your favorite build system, version of Spring Boot you want to use and then choose the required dependencies from a menu. Click the Generate Project button, and you have a ready-to-execute application.

Options you can choose using Spring Initializr are-

  1. Build System- Maven Project or Gradle Project
  2. Language- Java, Kotlin or Groovy
  3. Spring Boot version
  4. Project metadata- Group, Artifact and other Options like Name, Java version, packaging (Jar or War)
  5. Dependencies- To select the required dependencies in the form of starters.
Spring Initializr

Spring Boot application using Spring Initializr

In this example we’ll create a Hello world web application using Spring Initializr. For the project build system selected is Maven.

Since we are building a web application, in the Dependencies section type web, from the suggested options select ‘Spring Web Starter’ for the web application. This starter adds the dependencies required for creating a Spring web application and also includes Tomcat as the default embedded container.

Following image shows the selected options for the example-

Spring Initializr application

Click “Generate the project” and save the generated zip file when prompted. This zip file contains the generated Maven project based on the options you chose in Spring Initializr.

You can unzip the downloaded zip file, you should see the genrated project structure with a build file (pom.xml).

Import generated project

You can import generated Maven project to Eclipse IDE.

Select File – Import – Maven – Existing Maven Project

In the “Import Maven Projects” window, Select Root directory as the location where you have unzipped the downloaded zipped project structure.

Select the pom.xml file for the project and click Finish to start the import.

Spring Boot Spring Initializr

On opening the pom.xml you should see the Spring boot version, Java version as per your selection in Spring Initializr. Also the spring-boot-starter-web for the selected dependency.

Spring Initializr also adds-

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

spring-boot-maven-plugin which provides many convenient features-

  • It creates an executable jar (fat jar) by collecting all the jars on the classpath.
  • It searches for the public static void main() method to flag as a runnable class.
  • It provides a built-in dependency resolver that sets the version number to match Spring Boot dependencies. You can override any version you wish, but it will default to Boot’s chosen set of versions.
<?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 https://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.9.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>
  <groupId>org.netjs</groupId>
  <artifactId>SpringBootApp</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringBootApp</name>
  <description>Demo project for Spring Boot</description>

  <properties>
    <java.version>11</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>

In the generated project you’ll also find an application class with the main method-

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

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

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

  • @Configuration: Marks this class as a source of bean definitions for the application context.
  • @EnableAutoConfiguration: Tells Spring Boot to automatically start creating beans based on classpath settings, other beans, and various property settings. For example, if spring-webmvc is on the classpath, this annotation flags the application as a web application and activates key behaviors, such as setting up a DispatcherServlet.
  • @ComponentScan: Tells Spring to look for other components, configurations, and services in the base package, letting it find the controllers.

Main method in the class is the application entry point. The main method delegates to Spring Boot’s SpringApplication class by calling run method. It is the task of SpringApplication to bootstrap our application, starting Spring, which, in turn, starts the auto-configured Tomcat web server.

Rest Controller class

As you can see by selecting options in the Spring Initializr you have the build file with the appropriate starters and an application class in place.

We’ll add a rest controller class annotated with @RestController annotation to get the hello world functionality.

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

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

The @GetMapping annotation provides “routing” information here. It tells Spring that any HTTP request with the /name path should be mapped to the displayMessage method.

Running the Spring Boot Hello world Rest application

1. You can run this application as a Java application by executing the class with main method.

Right click SpringBootAppApplication – Run As – Java Application

That will start the SpringBootApp, initialize WebApplicationContext and Tomcat server.

You can access the application by entering http://localhost:8080/netjs

Here /netjs is the value for the name parameter.

2. spring-boot-starter-parent POM also provides a run goal that you can use to start the application. Type mvn spring-boot:run from the root project directory to start the application.

F:\NETJS\NetJS_2017\Spring Boot\SpringBootApp\SpringBootApp>mvn spring-boot:run

3. You can also create a completely self-contained executable jar file. We have already added spring-boot-maven-plugin in pom.xml for this.

To create an executable Jar run mvn package from the root project directory.

F:\NETJS\NetJS_2017\Spring Boot\SpringBootApp\SpringBootApp>mvn package

[INFO] Building jar: F:\NETJS\NetJS_2017\Spring Boot\SpringBootApp\SpringBootApp\target\SpringBootApp-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- spring-boot-maven-plugin:2.1.9.RELEASE:repackage (repackage) @ SpringBootApp ---
[INFO] Replacing main artifact with repackaged archive
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 31.979 s
[INFO] Finished at: 2019-10-08T12:18:08+05:30
[INFO] Final Memory: 23M/77M
[INFO] ------------------------------------------------------------------------

If you look in the target directory, you should see SpringBootApp-0.0.1-SNAPSHOT.jar. To run that application, use the java -jar command, as follows:

F:\NETJS\NetJS_2017\Spring Boot\SpringBootApp\SpringBootApp>java -jar target\SpringBootApp-0.0.1-SNAPSHOT.jar

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.9.RELEASE)

2019-10-08 12:20:07.395  INFO 11676 --- [           main] o.n.S.SpringBootAppApplication           : Starting SpringBootAppApplication v0.0.1-SNAPSHOT on user 
with PID 11676 (F:\NETJS\NetJS_2017\Spring Boot\SpringBootApp\SpringBootApp\target\SpringBootApp-0.0.1-SNAPSHOT.jar 
2019-10-08 12:20:07.410  INFO 11676 --- [           main] o.n.S.SpringBootAppApplication           : No active profile set, falling back to default profiles: default
2019-10-08 12:20:11.326  INFO 11676 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-10-08 12:20:11.607  INFO 11676 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-10-08 12:20:11.607  INFO 11676 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.26]
2019-10-08 12:20:12.190  INFO 11676 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-10-08 12:20:12.191  INFO 11676 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 4625 ms
2019-10-08 12:20:13.531  INFO 11676 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-10-08 12:20:14.328  INFO 11676 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-10-08 12:20:14.360  INFO 11676 --- [           main] o.n.S.SpringBootAppApplication           : Started SpringBootAppApplication in 9.324 seconds (JVM running for 12.267)

That's all for this topic Spring Boot Spring Initializr. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Spring Boot StandAlone (Console Based) Application Example
  2. Spring Boot spring-boot-starter-parent
  3. Spring MVC JSON as Response Example
  4. Spring NamedParameterJdbcTemplate Insert, Update And Delete Example
  5. Spring MVC Checkbox And Checkboxes Form Tag Example

You may also like-

  1. Spring XML Configuration Example
  2. Spring Object XML Mapping (OXM) Castor Example
  3. Passing Arguments to getBean() Method in Spring
  4. Spring Integration With Quartz Scheduler
  5. ListIterator in Java
  6. Parallel Stream in Java Stream API
  7. Producer-Consumer Java Program Using ArrayBlockingQueue
  8. Python Program to Display Fibonacci Series