1. Introduction
In this post, we'll create a minimal Java microservice using Spring Boot and Maven. We'll use Maven's archetype to bootstrap our project and add a simple REST endpoint using the embedded Tomcat server that comes with Spring Boot.
2. Generate Project Using Maven
You can use Spring Boot's official archetype or simply use the spring-boot-starter-parent and manually add dependencies.
Option 1: Use Maven Archetype (Manually Add Dependencies)
There’s no built-in official archetype for Spring Boot like there is for other frameworks, but you can generate a skeleton project like this:
mvn archetype:generate \
-DgroupId=com.example.micro \
-DartifactId=simple-microservice \
-DarchetypeArtifactId=maven-archetype-quickstart \
-DinteractiveMode=false
Then, modify the pom.xml to convert it into a Spring Boot project
3. Update pom.xml for Spring Boot
Replace the contents of pom.xml with:
<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.example.micro</groupId>
<artifactId>simple-microservice</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<!-- Web starter includes embedded Tomcat -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
4. Create Main Application Class
package com.example.micro;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SimpleMicroserviceApplication {
public static void main(String[] args) {
SpringApplication.run(SimpleMicroserviceApplication.class, args);
}
}
5. Add a REST Controller
package com.example.micro.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello from Spring Boot Microservice!";
}
}
6. Run the Application
mvn spring-boot:run
7. Wrap-up
And that’s it! You now have a working microservice with a REST endpoint running on embedded Tomcat, created entirely from the command line using Maven.
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.