Spring Boot Getting Started Tutorial – HelloWorld Example

In this Spring Boot Getting Started Tutorial, I will share two ways to fastly create a web application based on Spring Boot.

As we know, Spring boot is one increasing popular Spring framework module, which provides rapid application development features to the Spring framework.

Spring Boot makes it easy to create stand-alone, production-grade Spring-based Applications that you can run. The important thing is that most Spring Boot applications only need very little Spring configuration.

Spring boot modules

The prerequisites

In this tutorial, the prerequisites are you have installed:

Using Maven to build a simple Spring Boot web application

In this section, I will show how to develop a simple Spring Boot “Hello World!” web app by using Maven. By this way step by step to build your Spring Boot project, helping to understand some key features of Spring Boot.

Check Java and Maven installed rightly

The first thing is to figure out you have installed the valid versions of Java. Run the java -version command in terminal to check it.

$ java -version
java version "13.0.2" 2020-01-14
Java(TM) SE Runtime Environment (build 13.0.2+8)
Java HotSpot(TM) 64-Bit Server VM (build 13.0.2+8, mixed mode, sharing)

The second thing you should ensure is the Maven had been installed rightly. Run the mvn -v command in terminal to check it.

$ mvn -v
Apache Maven 3.6.3 (cecedd343002696d0abb50b32b541b8a6ba2883f)
Maven home: /usr/local/maven/maven-3.6.3
Java version: 13.0.2, vendor: Oracle Corporation, runtime: /Library/Java/JavaVirtualMachines/jdk-13.0.2.jdk/Contents/Home

You will see similar info like that. If the Maven not installed rightly, see how to install Maven to install it.

Creating a POM file

First, create a project folder on your computer. Then enter the project folder, create a pom.xml file. And add the following content into it, save and quit the 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>myproject</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.5.RELEASE</version>
    </parent>

    <description/>
    <developers>
        <developer/>
    </developers>
    <licenses>
        <license/>
    </licenses>
    <scm>
        <url/>
    </scm>
    <url/>

    <!-- Additional lines to be added here... -->

</project>

The pom.xml is the recipe used to build the project. We will add some classpath dependencies into it.

Adding Classpath Dependencies

Spring Boot provides many starters to help add jars to your classpath. The spring-boot-starter-parent is a special starter that provides useful Maven defaults. You can add the dependencies that need in your project.

To create simple MVC application all you need to add is spring-boot-starter-web dependency. Open your pom.xml and add the spring-boot-starter-web dependency immediately below the parent section, save and quit it.

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

You can run mvn dependency:tree command to see dependencies added in the project.

$ mvn dependency:tree
[INFO] com.example:myproject:jar:0.0.1-SNAPSHOT
[INFO] \- org.springframework.boot:spring-boot-starter-web:jar:2.2.5.RELEASE:compile
[INFO]    +- org.springframework.boot:spring-boot-starter:jar:2.2.5.RELEASE:compile
[INFO]    |  +- org.springframework.boot:spring-boot:jar:2.2.5.RELEASE:compile
...

Create a Java file

We need to create a Java file in the src/main/java folder. Here, I named the Java file as FaqgeekExample.java, and add the following code:

import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.web.bind.annotation.*;

@RestController
@EnableAutoConfiguration
public class FaqgeekExample {

	@RequestMapping("/")
	String home(){
		return "Hello faqgeek guys!";
	}

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

Although the code is not much here, quite a lot of work is going on.

  • @RestController – A stereotype annotation that provides hints for programmers reading the code and for Spring that the class plays a specific role. In this demo, the class is a web @Controller, so Spring considers it when handling incoming web requests.
  • @EnableAutoConfiguration – A annotation tells Spring Boot to “guess” how you 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 assumes that you are developing a web application and sets up Spring accordingly.
  • @RequestMapping – A annotation provides “routing” information to map the request path with methods. Here, the HTTP request with the / path should be mapped to the home method.

In this Spring Boot web application, execution start with main() method. The main method delegates to Spring Boot’s SpringApplication class by calling runSpringApplication bootstraps our application, starting Spring, which, in turn, starts the auto-configured Tomcat web server. 

About @SpringBootApplication annotation

@SpringBootApplication
public class HelloWorldApplication {

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

}

When it comes to Spring Boot startup class, we had to introduce @SpringBootApplicationannotation , this annotation-related code is as follows:

package org.springframework.boot.autoconfigure;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
        @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
        @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
   ......
}
package org.springframework.boot;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {

}

It can be seen that @SpringBootApplication can be seen as a collection of  @Configuration@EnableAutoConfiguration@ComponentScanannotations. According to the SpringBoot official website, the effects of these three annotations are:

  • @EnableAutoConfiguration: Enabling SpringBoot’s Auto-Configuration Mechanism
  • @ComponentScan: Scan for beans annotated with @Component@Service@Controller). By default, annotations will scan all classes in the package where the class is located.
  • @Configuration: Allows you to register additional beans in the context or import other configuration classes.

So @SpringBootApplicationis a combination of several important annotations.

why we need it? 

For avoids us having to write some necessary comments every time we develop a Spring Boot project. It saves a lot of time and energy. 

Run the project

By now, you have built the simple Spring Boot web application. Go to the root directory of project, and type mvn spring-boot:run to run the project. The successful running info like the following:

$ mvn spring-boot:run
[INFO] Scanning for projects...
[INFO] -----------------------< com.example:myproject >------------------------
[INFO] Building myproject 0.0.1-SNAPSHOT
[INFO] --- spring-boot-maven-plugin:2.2.5.RELEASE:run (default-cli) @ myproject ---
[INFO] Attaching agents: []

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

Open your web browser to visit localhost:8080 or 127.0.0.1:8080. You will see the output information:

Hello faqgeek guys!

If you want to quit or stop the app, just press ctrl-c.

Run the project by executable JAR

Run the mvn package command to generate an executable JAR file in the target folder.

$ mvn package
[INFO] Scanning for projects...
[INFO] ---------------------------< com.faqgeek:demo >---------------------------
[INFO] Building demo 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] --- maven-resources-plugin:3.1.0:resources (default-resources) @ demo ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
...

Then, to run the project by executing the jar file.

$ java -jar target/your-project-name-0.0.1-SNAPSHOT.jar

Visit localhost:8080 on a browser, you will see the same output info.

Using IDE to build a Spring Boot application

In fact, you can create a Spring Boot application directly through IDE, such as Eclipse and Idea.

This way is faster and the IDE helps build project structure.

Build project by Idea IDE

The steps to build Spring Boot by Idea IDE as the following:

  1. File -> New -> Project … The box for creating a new project pops up.
  2. Select Spring Initializr and Project SDK java version, then click Next.
  3. After filling in the relevant content, click Next to select the dependent packages and then click Next.
  4. Finally, confirm that the information is correct and click Finish.
Build spring boot project by Idea IDE

The basic structure of Spring Boot project:

  • src/main/java  program development and main program entry
  • src/main/resources  configuration file
  • src/test/java  test program

The directory structure suggested by Spring Boot:

com
  +- faqgeek
    +- myproject
      +- Application.java
      |
      +- model
      |  +- Customer.java
      |  +- CustomerRepository.java
      |
      +- service
      |  +- CustomerService.java
      |
      +- controller
      |  +- CustomerController.java
      |
  • Application.java is recommended to be placed in the root directory, mainly used to do some framework configuration
  • Model directory is mainly used for entities and data access layer (Repository)
  • Service layer with some business code
  • Controller responsible for page access control

Using the default configuration can save a lot of configuration, of course, you can also change it according to your preference.

The following steps are similar to the first method. Try to do it according to your requirements.

References

Leave a Comment