8 min read

Spring boot Hello World!

January 07, 2018

This tutorial helps you to build your first spring boot web application from the scratch. We will get in depth some key features of spring boot by breaking down this hello world project line by line.

At the end of this post you would have learnt how to write a A simple application that prints hello world! in your web browser.

Before getting started

  • JDK 1.8 or later
  • Maven 3.2+
  • about 15 minutes of your time

Open your command and check if you are getting the results somewhat similar for java and maven version checks.

$ java -version
java version "1.8.0_144"
Java(TM) SE Runtime Environment (build 1.8.0_144-b01)
Java HotSpot(TM) 64-Bit Server VM (build 25.144-b01, mixed mode)
$ mvn -v
Apache Maven 3.5.0 (ff8f5e7444045639af65f6095c62210b5713f426; 2017-04-04T01:09:06+05:30)
Maven home: C:\apps\apache-maven-3.5.0
Java version: 1.8.0_144, vendor: Oracle Corporation
Java home: C:\Program Files\Java\jdk1.8.0_144\jre
Default locale: en_IN, platform encoding: Cp1252
OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows"

The pom.xml

We need to start by creating a Maven pom.xml file. If you have not heard already, pom.xml lets maven know which jar files ( AKA dependencies ) to include while compiling and building the project. This file plays critical role in spring boot as each dependency from spring artifact group we add here will more likely enable a preconfigured module such as Web, Database, MQ, Scheduling ETC. For now we will stick with only the Web module.

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

 <groupId>com.springhow.example</groupId>
 <artifactId>hello-world</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>

 <name>hello-world</name>
 <description>Demo project for Spring Boot</description>

 <parent>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-parent</artifactId>
   <version>1.5.9.RELEASE</version>
   <relativePath/> <!-- lookup parent from repository -->
 </parent>

 <properties>
   <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
   <java.version>1.8</java.version>
 </properties>
</project>

The concept of starters

Spring boot modules are activated based on dependencies called starters. For each component like web, database, Message Queue etc., there is a starter available for us to make use of. They can straightway be included to the project in terms of maven or gradle dependencies.

In the above xml, the parent section includes a special starter dependency called spring-boot-starter-parent This takes care of all internal dependencies needed for spring boot to work. It also provides the very basic maven defaults.

This parent module is also responsible for versioning of the internal dependencies.

At this point in time, you can run the command mvn dependency:tree and you can see that the spring-boot-starter-parent provides no dependencies by itself. Let’s edit our pom.xml to add the spring-boot-starter-web dependency under our dependencies tag like its been shown below.

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

If you run mvn dependency:tree again, you will see that the dependency list has grown,It will now include jar files for tomcat server and other jar files to support the spring boot itself.

The Main class

We can complete our tutorial by creating a file under src/main/java/ called HelloWorldApplication.java.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
public class HelloWorldApplication {

  @RequestMapping("/")
  String helloWorld() {
    return "Hello World!";
  }

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

Lets run the application before getting further by submitting the command mvn spring-boot:run from the root of your project directory. The output would be something like the below

$ mvn spring-boot:run
mvn spring-boot:run
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building hello-world 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
.
.More maven and spring -boot initialisation logs here
.
.
2017-12-16 22:45:55.495 INFO 10728 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-12-16 22:45:55.626 INFO 10728 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2017-12-16 22:45:55.698 INFO 10728 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-12-16 22:45:55.703 INFO 10728 --- [ main] c.s.e.helloworld.HelloWorldApplication : Started HelloWorldApplication in 3.299 seconds (JVM running for 6.985)

Now open http://localhost:8080 on your browser and it should show

Hello World!

To exit the application press Ctrl + C.

Breaking down the little things

Now that we have seen the application in action, lets break down the code line by line, Literally.

The @Annotations

Key features of spring boot( Spring to be specific, But whatever ). These annotations help spring decide on how the bean need to be auto configured internally. You can read more about annotations here.

@SpringBootApplication

This annotation is responsible for enabling auto configuration of spring beans. This advices spring to look through the class path for beans to initialize and manage. This is a class level annotation.

@RestController and @RequestMapping

The @RestController and @RequestMapping annotations are Spring MVC annotations (they are not specific to Spring Boot). The difference here is that we have no effort setting up any MVC specific configurations. The starter for web takes care of it with its default auto configuration.

The Main method

The final ingredient in this recipe is the one line that ties all of these things to gather. SpringApplication.run (HelloWorldApplication.class, args);

The utility class SpringApplication from the spring-boot-starter dependency boots the application and auto configures it. The importance here is that the run method will normally take two arguments, One the class that needs to be bootstrapped and the arguments which are passed part of calling the application.

Building the application

Did maven just run my application?

We ran the application straight away using maven command. But maven is supposed to be a build tool right?. Yes it is and much more. The spring-boot-starter-parent has an useful rungoal which can be used for the developers to test it straight away from their development environment even before packaging the application.

Building the JAR

Spring boot applications can be packaged into an executable jar file. However, there is one problem. Maven needs to know how to create a jar that will contain other jar files as their dependencies. There comes spring-boot-maven-plugin which does just that. To use this plugin add the following to your pom.xml after the dependencies section

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

Save your pom.xml and run mvn package from command line. This will create a file approximately 15MB in your maven target/ folder along with a original.jar file which was created just before spring repackaged your application.

To run that application, use the java -jar command: java -jar target/hello-world-0.0.1-SNAPSHOT.jar

$ java -jar target/hello-world-0.0.1-SNAPSHOT.jar
 . ____ _ __ _ _
 /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/ ___)| |_)| | | | | || (_| | ) ) ) )
 ' |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot :: (v1.5.9.RELEASE)
2017-12-16 23:39:40.230 INFO 12112 --- [ main] c.s.e.helloworld.HelloWorldApplication : Starting HelloWorldApplication v0.0.1-SNAPSHOT on MACHINE with PID 12112 (C:\test\hello-world\target\hello-world-0.0.1-SNAPSHOT.jar started by raja in C:\test\hello-world)
2017-12-16 23:39:40.250 INFO 12112 --- [ main] c.s.e.helloworld.HelloWorldApplication : No active profile set, falling back to default profiles: default
2017-12-16 23:39:40.416 INFO 12112 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@2cdf8d8a: startup date [Sat Dec 16 23:39:40 IST 2017]; root of context hierarchy
2017-12-16 23:39:42.716 INFO 12112 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-12-16 23:39:42.733 INFO 12112 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2017-12-16 23:39:42.735 INFO 12112 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.23
2017-12-16 23:39:42.922 INFO 12112 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2017-12-16 23:39:42.922 INFO 12112 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2509 ms
2017-12-16 23:39:43.140 INFO 12112 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2017-12-16 23:39:43.146 INFO 12112 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/]
2017-12-16 23:39:43.147 INFO 12112 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/]
2017-12-16 23:39:43.147 INFO 12112 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/]
2017-12-16 23:39:43.147 INFO 12112 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/]
2017-12-16 23:39:43.554 INFO 12112 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@2cdf8d8a: startup date [Sat Dec 16 23:39:40 IST 2017]; root of context hierarchy
2017-12-16 23:39:43.689 INFO 12112 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto java.lang.String com.springhow.example.helloworld.HelloWorldApplication.helloWorld()
2017-12-16 23:39:43.693 INFO 12112 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-12-16 23:39:43.693 INFO 12112 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-12-16 23:39:43.737 INFO 12112 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/∗∗] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-12-16 23:39:43.737 INFO 12112 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/∗∗] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-12-16 23:39:43.808 INFO 12112 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/∗∗/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-12-16 23:39:44.027 INFO 12112 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2017-12-16 23:39:44.131 INFO 12112 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-12-16 23:39:44.140 INFO 12112 --- [ main] c.s.e.helloworld.HelloWorldApplication : Started HelloWorldApplication in 4.687 seconds (JVM running for 5.222)

To gracefully exit the application hit Ctrl + C.

If you want to create your own Spring Boot-based project, visit Spring Initializr page , fill in your project details, pick your options, and you can download either a Maven build file, or a bundled up project as a zip file.

Raja Anbazhagan

About the author

Raja is a Software Engineer with over 7 years of experience in working with Enterprise Java applications. Lately, He is focused in cloud-based Java applications and serverless technologies. He spends his spare time in stackoverflow.

Browse Categories