How to Create Spring Boot project with Maven

In this article we will see how to create a Spring Boot project with Maven and Import it in Eclipse. In this section we will discuss, how to create an application from scratches using Spring Boot, a step by step implementation guide is provides below:

1) Create Java project with Maven


$ mvn archetype:generate -DgroupId=com.tb.java -DartifactId=ApiServer -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

2) Convert to eclipse


$ cd ApiServer/
$ mvn eclipse:eclipse

3) Import project in Eclipse

4) Changes in pom.xml

Import newly created Java project in Eclipse, you will find a pom.xml file, replace this with the content written below:
<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/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.tb.java</groupId>
	<artifactId>ApiServer</artifactId>
	<packaging>jar</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>ApiServer</name>
	<url>http://maven.apache.org</url>
	<properties>
		<java.version>1.8</java.version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.4.RELEASE</version>
	</parent>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<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>repository.spring.release</id>
			<name>Spring GA Repository</name>
			<url>http://repo.spring.io/release</url>
		</repository>
	</repositories>
</project>

What is "spring-boot-starter-web" dependency ?

In order to add web compatibilities to the project we just need to add "spring-boot-starter-web" as shown below, everything else related to required dependencies and their veriosn will be handled by Spring Boot itself.
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>

What is spring-boot-maven-plugin ?

The Spring Boot Maven Plugin provides Spring Boot support in Maven, letting you package executable jar or war archives and run an application ?in-place?. To use it, you must use Maven 3.2 (or later).
<build>
	<plugins>
		<plugin>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-maven-plugin</artifactId>
		</plugin>
	</plugins>
</build>

4) Create a spring boot application launch class

/ApiServer/src/main/java/com/tb/java/App.java
package com.tb.java;

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

/**
 * Hello world!
 *
 */
@SpringBootApplication
public class App {
	public static void main(String[] args) {
		ApplicationContext context = SpringApplication.run(App.class, args);
		System.out.println("Hello !");
	}
}
In this class we have instantiated ApplicationContext, this will load all the Spring beans as per the configuration. We have also passed command line arguments to it, that will convert them to spring properties.

@SpringBootApplication Annotation

@SpringBootApplication Annotation added to "App", is a combined annotation for following three annotations:

1) @SpringBootConfiguration

It a new version of "@Configuration" annotation intriduced in Boot 2.0 with exactly same working as "@Configuration", it indicates that the class will be used as an configuratin class and shall be scanned for further configurations and bean definitions

2) @EnableAutoConfiguration

This annotation is used to enable auto-configuration of the Spring Application Context, attempting to guess and configure beans that you are likely to need. Auto-configuration can be disabled using one of the two methods:

2.1) Using "excludeName" in the annotation as shown below: @EnableAutoConfiguration(excludeName = {"multipartResolver","myBean"})
2.2) Using the spring.autoconfigure.exclude property in properties file.

3) @ComponentScan

This annotation does the same work as "context:component-scan" does in xml based configuration, basePackageClasses() or basePackages() may be specified to define specific packages to scan. In absence of a specific packages defination, scanning will occur from the package of the class that declares this annotation.

5) Adding a web Controller

We can now add a Controller to the application to handle web requests: /src/main/java/com/tb/java/ApplicationController.java
package com.tb.java;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ApplicationController {

	@RequestMapping("/name")
	public String getName() {
		return "Simple Application";
	}
}
@RestController annotation contains two annotations in it, @Controller and @ResponseBody, there is no need to add @ResponseBody in each @RequestMapping explicitly to return data rather than a view.

6) Run a spring boot (Maven) application

In order to run a boot application, following command can be used from the project home dircetory:

$ mvn spring-boot:run
This will print logs something like this, an embeded Tomcat will be started on Port 8080, with the application deployed on it.

[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building ApiServer 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] >>> spring-boot-maven-plugin:2.0.4.RELEASE:run (default-cli) > test-compile @ ApiServer >>>

...
...
...


[INFO] --- spring-boot-maven-plugin:2.0.4.RELEASE:run (default-cli) @ ApiServer ---

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

....
....
....

2018-09-12 14:55:14.723  INFO 18861 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2018-09-12 14:55:14.728  INFO 18861 --- [           main] com.tb.java.App                          : Started App in 2.824 seconds (JVM running for 6.412)
Hello !

7) Testing URL mapping

We can now test a url response added in "ApplicationController.java"

$ curl http://localhost:8080/name
Simple Application

About The Author

Nagesh Chauhan

Nagesh Chauhan has 8+ years of software design and development experience in variety of technologies like - Core Java, Java 8 (Streams, Lambda), J2EE (Servlet, JSP), Spring Framework (MVC, IOC, JDBC, SECURITY etc), Spring Boot and Microservices, Kafla, Redis, Cassandra and Spark.