Monday, October 7, 2019

Spring Boot Hello World Web Application Example

In this Spring Boot beginner tutorial we’ll see how to create a Hello world web application using Spring Boot.


Maven Dependencies

Though there is an option to select dependencies using Spring Initializr but for this example we’ll add dependencies ourselves in pom.xml.

To see how to create a Maven project refer this post- Creating Maven Project in Eclipse

<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>org.netjs</groupId>
    <artifactId>SpringBootNetjs</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringBootNetjs</name>
    <description>Spring Boot project</description>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.9.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-web</artifactId>
           </dependency>
       </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

In the parent section of the POM spring-boot-starter-parent is added which is a special starter that provides useful Maven defaults. It also provides a dependency-management section so that you can omit version tags for the dependencies.

Each release of Spring Boot provides a curated list of dependencies that it supports, you do not need to provide a version for any of these dependencies in your build configuration, as Spring Boot manages that for you. The curated list contains all the spring modules that you can use with Spring Boot as well as a refined list of third party libraries. The list is available as a standard Bills of Materials (spring-boot-dependencies) that can be used with both Maven and Gradle.

spring-boot-starter-parent provides no dependencies by itself. There are other “Starters” providing dependencies that you may need when developing a specific type of application. Since we are developing a web application, we add a spring-boot-starter-web dependency. This starter adds Spring MVC, Jackson jars and also an embedded Tomcat server.

The Spring Boot Maven plugin 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.

Rest Controller class

We’ll add a rest controller class annotated with @RestController annotation that makes this class eligible for component scanning and being registered as Spring bean. @RestController annotation itself is also annotated with @ResponseBody so returned value is returned as part of response body rather than rendered using views.

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.

Create an Application class

We'll also create an Application class with the components to run our Spring Boot hello world example.

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

@SpringBootApplication
public class HelloWorldApp {
    public static void main(String[] args) {
        SpringApplication.run(HelloWorldApp.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.

You need to pass HelloWorldApp.class as an argument to the run method to tell SpringApplication which is the primary Spring component.

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 HelloWorldApp – Run As – Java Application

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

2019-10-05 12:25:48.105  INFO 18192 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-10-05 12:25:48.115  INFO 18192 --- [           main] org.netjs.springboot.HelloWorldApp       : Started HelloWorldApp in 12.928 seconds (JVM running for 16.446)
2019-10-05 12:28:47.871  INFO 18192 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-10-05 12:28:47.873  INFO 18192 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2019-10-05 12:28:47.928  INFO 18192 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 54 ms

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

Here /netjs is the value for the name parameter.

Spring Boot Hello World

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\Spring WorkSpace\SpringBootNetjs>mvn spring-boot:run
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building SpringBootNetjs 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------

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\Spring WorkSpace\SpringBootNetjs>mvn package
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building SpringBootNetjs 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
..
..
[INFO] Building jar: F:\netjs\Spring WorkSpace\SpringBootNetjs\target\SpringBootNetjs-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- spring-boot-maven-plugin:2.1.9.RELEASE:repackage (repackage) @ SpringBootNetjs ---
[INFO] Replacing main artifact with repackaged archive
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 16.889 s
[INFO] Finished at: 2019-10-05T12:39:28+05:30
[INFO] Final Memory: 21M/74M
[INFO] ------------------------------------------------------------------------

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

F:\netjs\Spring WorkSpace\SpringBootNetjs>java -jar target\SpringBootNetjs-0.0.1-SNAPSHOT.jar
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.9.RELEASE)

2019-10-05 12:43:30.150  INFO 19852 --- [           main] org.netjs.springboot.HelloWorldApp       : Starting HelloWorldApp v0.0.1-SNAPSHOT on user with PID 19852 (F:\netjs\Spring WorkSpace\SpringBootNetjs\target\SpringBootNetjs-0.0.1-SNAPSHOT.jar started by netjs in F:\netjs\Spring WorkSpace\SpringBootNetjs)
2019-10-05 12:43:30.180  INFO 19852 --- [           main] org.netjs.springboot.HelloWorldApp       : No active profile set, falling back to default profiles: default
2019-10-05 12:43:33.807  INFO 19852 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-10-05 12:43:34.028  INFO 19852 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-10-05 12:43:34.034  INFO 19852 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.26]
2019-10-05 12:43:34.649  INFO 19852 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-10-05 12:43:34.651  INFO 19852 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 4175 ms
2019-10-05 12:43:35.977  INFO 19852 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-10-05 12:43:36.960  INFO 19852 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-10-05 12:43:36.993  INFO 19852 --- [           main] org.netjs.springboot.HelloWorldApp       : Started HelloWorldApp in 9.854 seconds (JVM running for 11.887)

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

>>>Return to Spring Tutorial Page


Related Topics

  1. Spring Web MVC Java Configuration Example
  2. Spring MVC Dot (.) Truncation Problem With @PathVariable Annotation
  3. Spring Transaction Management JDBC Example Using @Transactional Annotation
  4. Sending Email Using Spring Framework Example
  5. Select Query Using NamedParameterJDBCTemplate in Spring Framework

You may also like -

  1. How to Inject Prototype Scoped Bean in Singleton Bean
  2. How to Inject Null And Empty String Values in Spring
  3. Using @Conditional Annotation in Spring Framework
  4. Using Spring Profiles to Switch Environment
  5. Java Collections Interview Questions And Answers
  6. BigDecimal in Java
  7. HDFS Federation in Hadoop Framework
  8. Python Exception Handling Tutorial