Developing your first Spring Boot application Hello World

Hello friends!!! Let’s develop a simple “Hello World!” web application in Java that highlights some of Spring Boot’s key features. We’ll use Maven to build this project since most IDEs support it.
We are using intializr to quick create project so we can choose either via one of following Initializr interfaces to create web application project structure to initiate.

Spring Boot application Hello World

Here we are going to use web interface to create project structure for “Hello World” web application. As below figure I have created
Developing your first Spring Boot application Hello World
Once the project has been created, you should have a project structure similar to that shown in figure below.
Spring-boot-hello-world

Examining a newly initialized Spring Boot project

Now let’s slow down and take a closer look at what’s contained in the initial project. First thing to noticed in the project structure follow the layout of Maven or Gradle project That is, the main application code is placed in the src/main/java branch of the directory tree, resources are placed in the src/main/ resources branch, and test code is placed in the src/test/java branch At this point we don’t have any test resources, but if we did we’d put them in src/test/resources.
Let see auto generated files in deeper:
Pom.xml: The Maven build specification
This is the recipe that will be used to build your project.
<?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.dineshonjava</groupId>
 <artifactId>SpringBootHelloWorld</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>

 <name>SpringBootHelloWorld</name>
 <description>SpringBootHelloWorld project for Spring Boot</description>

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

 <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <java.version>1.8</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>
 
 <repositories>
  <repository>
   <id>spring-snapshots</id>
   <name>Spring Snapshots</name>
   <url>https://repo.spring.io/snapshot</url>
   <snapshots>
    <enabled>true</enabled>
   </snapshots>
  </repository>
  <repository>
   <id>spring-milestones</id>
   <name>Spring Milestones</name>
   <url>https://repo.spring.io/milestone</url>
   <snapshots>
    <enabled>false</enabled>
   </snapshots>
  </repository>
 </repositories>
 <pluginRepositories>
  <pluginRepository>
   <id>spring-snapshots</id>
   <name>Spring Snapshots</name>
   <url>https://repo.spring.io/snapshot</url>
   <snapshots>
    <enabled>true</enabled>
   </snapshots>
  </pluginRepository>
  <pluginRepository>
   <id>spring-milestones</id>
   <name>Spring Milestones</name>
   <url>https://repo.spring.io/milestone</url>
   <snapshots>
    <enabled>false</enabled>
   </snapshots>
  </pluginRepository>
 </pluginRepositories>

</project>
Spring Boot provides a number of “Starters” that make easy to add jars to your classpath. Our sample application has already used spring-boot-starter-parent in the parent section of the POM. The spring-boot-starter-parent is a special starter that provides useful Maven defaults.
SpringBootHelloWorldApplication.java
The application’s bootstrap class and primary Spring configuration class
package com.dineshonjava;

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

@RestController
@SpringBootApplication
public class SpringBootHelloWorldApplication {
 
 @RequestMapping("/")
    String home() {
        return "Hello World!";
    }
 
 public static void main(String[] args) {
  SpringApplication.run(SpringBootHelloWorldApplication.class, args);
 }
}

The @RestController and @RequestMapping annotations

@RestController is known as a stereotype annotation. The @RequestMapping annotation provides “routing” information. It is telling Spring that any HTTP request with the path “/” should be mapped to the home method. The @RestController annotation tells Spring to render the resulting string directly back to the caller.

The @SpringBootApplication annotation

The @SpringBootApplication enables Spring component-scanning and Spring Boot auto-configuration. In fact, @SpringBootApplication combines three other useful annotations:
  • Spring’s @Configuration—Designates a class as a configuration class using Spring’s Java-based configuration. Although we won’t be writing a lot of configuration in this tutorial, we’ll favor Java-based configuration over XML configuration when we do.
  • Spring’s @ComponentScan—Enables component-scanning so that the web controller classes and other components you write will be automatically discovered and registered as beans in the Spring application context. Here we’ll write a simple Spring MVC controller that will be annotated with @RestController so that component-scanning can find it.
  • Spring Boot’s @EnableAutoConfiguration— This annotation tells Spring Boot to “guess” how you will want to configure Spring, based on the jar dependencies that you have added. Since spring-boot-starter-web added Tomcat and Spring MVC, the auto-configuration will assume that you are developing a web application and setup Spring accordingly.
application.properties—A place to configure application and Spring Boot properties. The application.properties file given to you by the Initializr is initially empty. In fact, this file is completely optional, so you could remove it completely without impacting the application.
Suppose we are adding following line to this property file
server.port=1208
With this line, you’re configuring the embedded Tomcat server to listen on port 1208 instead of the default port 8080.
SpringBootHelloWorldApplicationTests.java—A basic integration test class
package com.dineshonjava;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootHelloWorldApplicationTests {

 @Test
 public void contextLoads() {
 }

}

In a typical Spring integration test, you’d annotate the test class with @Context- Configuration to specify how the test should load the Spring application context. But in order to take full advantage of Spring Boot magic, the @SpringApplication- Configuration annotation should be used instead.
The “main” method:
The final part of our application is the main method. This is just a standard method that follows the Java convention for an application entry point. Our main method delegates to Spring Boot’s SpringApplication class by calling run. SpringApplication will bootstrap our application, starting Spring which will in turn start the auto-configured Tomcat web server.
Running the example
Type mvn spring-boot:run from the root project directory to start the application:
.   ____          _            __ _ _
 / / ___’_ __ _ _(_)_ __  __ _
( ( )___ | ‘_ | ‘_| | ‘_ / _` |
 /  ___)| |_)| | | | | || (_| |  ) ) ) )
  ‘  |____| .__|_| |_|_| |___, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::            (v1.4.0.RC1)
2016-07-14 08:54:35.959  INFO 12868 — [           main] c.d.SpringBootHelloWorldApplication      : Starting SpringBootHelloWorldApplication on NODTBSL206AG with PID 12868 (started by Dinesh.Rajput in D:personal dataspring-boot-workspaceSpringBootHelloWorld)
2016-07-14 08:54:35.961  INFO 12868 — [           main] c.d.SpringBootHelloWorldApplication      : No active profile set, falling back to default profiles: default
2016-07-14 08:54:36.096  INFO 12868 — [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1809907: startup date [Thu Jul 14 08:54:36 IST 2016]; root of context hierarchy

 

2016-07-14 08:54:39.630  INFO 12868 — [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
If you open a web browser to localhost:8080 you should see the following output:
Spring-boot-hello-world

Creating an executable jar

Let’s finish our example by creating a completely self-contained executable jar file that we could ruSn in production. Executable jars (sometimes called “fat jars”) are archives containing your compiled classes along with all of the jar dependencies that your code needs to run.
To create an executable jar we need to add the spring-boot-maven-plugin to our pom.xml. Insert the following lines just below 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 the command line:
D:personal dataspring-boot-workspaceSpringBootHelloWorld>mvn package
[INFO] Scanning for projects…
[INFO]
[INFO] ————————————————————————
[INFO] Building SpringBootHelloWorld 0.0.1-SNAPSHOT
[INFO] ————————————————————————
[INFO]
[INFO] — maven-resources-plugin:2.6:resources (default-resources) @ SpringBoot
HelloWorld —
[INFO] Using ‘UTF-8’ encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO] Copying 0 resource
[INFO]
[INFO] — maven-compiler-plugin:3.5.1:compile (default-compile) @ SpringBootHel
loWorld —
[INFO] Nothing to compile – all classes are up to date
If you look in the target directory you should see SpringBootHelloWorld -0.0.1-SNAPSHOT.jar.
To run that application, use the java -jar command:
$ java -jar target/ SpringBootHelloWorld -0.0.1-SNAPSHOT.jar
/ / ___’_ __ _ _(_)_ __  __ _
( ( )___ | ‘_ | ‘_| | ‘_ / _` |
 /  ___)| |_)| | | | | || (_| |  ) ) ) )
  ‘  |____| .__|_| |_|_| |___, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::            (v1.4.0.RC1)
2016-07-14 08:54:35.959  INFO 12868 — [           main] c.d.SpringBootHelloWorldApplication      : Starting SpringBootHelloWorldApplication on NODTBSL206AG with PID 12868 (started by Dinesh.Rajput in D:personal dataspring-boot-workspaceSpringBootHelloWorld)
2016-07-14 08:54:35.961  INFO 12868 — [           main] c.d.SpringBootHelloWorldApplication      : No active profile set, falling back to default profiles: default
2016-07-14 08:54:36.096  INFO 12868 — [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1809907: startup date [Thu Jul 14 08:54:36 IST 2016]; root of context hierarchy
2016-07-14 08:54:39.630  INFO 12868 — [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)

 Summary

By taking advantage of Spring Boot starter dependencies and auto-configuration, you can more quickly and easily develop Spring applications. Starter dependencies help you focus on the type of functionality your application needs rather than on the specific libraries and versions that provide that functionality. Meanwhile, auto-configuration frees you from the boilerplate configuration that is common among Spring applications without Spring Boot.
Happy Spring Boot Learning!!! 🙂
Previous
Next