Using Enums for Configuration Management in Spring Boot
The article shows how to replace hard‑coded strings in Spring Boot configuration files with type‑safe Java enums, using @ConfigurationProperties to bind YAML values to enum fields, thereby improving readability, maintainability, and eliminating magic numbers, illustrated through a user‑role example with controller and Thymeleaf view.
Configuration management is a key step in ensuring that a Spring Boot application can run smoothly in different environments. Configuration files such as application.yml or application.properties store items like database URLs, usernames, passwords, server ports, and API keys.
Hard‑coding these values as plain strings or numbers makes the code hard to read and maintain. Defining a fixed set of values with a Java enum improves readability and eliminates the risk of magic numbers.
By combining @ConfigurationProperties with enums, developers can map external configuration items directly to strongly‑typed Java fields, achieving a flexible and maintainable configuration scheme.
Important aspects of configuration management
Readability : Using enums makes the purpose of each value clear.
Maintainability : Changes are made in one place instead of scattered literals.
Avoid hard‑coding : Enums prevent magic numbers and strings.
Concrete example
The following Maven pom.xml defines the required dependencies:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>The application.yml file defines user‑type mappings:
spring:
datasource:
url: jdbc:mysql://localhost:3306/your_database
username: your_username
password: your_password
server:
port: 8080
app:
user-type:
admin: ADMIN
user: USER
guest: GUESTThe enum UserTypeEnum lists possible user roles with Chinese descriptions:
public enum UserTypeEnum {
ADMIN("管理员"),
USER("普通用户"),
GUEST("游客"),
VIP("VIP用户"),
MODERATOR("版主");
private final String description;
UserTypeEnum(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
}A configuration class uses @ConfigurationProperties(prefix = "app") to bind the YAML values to Java fields, nesting static classes for user type, database, and server settings:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import com.icoderoad.enumconfig.enums.UserTypeEnum;
import lombok.Data;
@Data
@Component
@ConfigurationProperties(prefix = "app")
public class AppConfig {
private UserType userType;
private Database database;
private Server server;
@Data
public static class UserType {
private UserTypeEnum admin;
private UserTypeEnum user;
private UserTypeEnum guest;
private UserTypeEnum vip;
private UserTypeEnum moderator;
}
@Data
public static class Database {
private String url;
private String username;
private String password;
}
@Data
public static class Server {
private int port;
}
}The controller injects AppConfig and adds each description to the model for rendering:
import com.example.demo.config.AppConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class UserController {
@Autowired
private AppConfig appConfig;
@GetMapping("/user-types")
public String getUserTypes(Model model) {
model.addAttribute("adminType", appConfig.getUserType().getAdmin().getDescription());
model.addAttribute("userType", appConfig.getUserType().getUser().getDescription());
model.addAttribute("guestType", appConfig.getUserType().getGuest().getDescription());
model.addAttribute("vipType", appConfig.getUserType().getVip().getDescription());
model.addAttribute("moderatorType", appConfig.getUserType().getModerator().getDescription());
return "index";
}
}The Thymeleaf template index.html displays the role and its description in a table:
<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用户类型</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h1 class="mt-5">用户类型</h1>
<table class="table table-bordered mt-3">
<thead>
<tr><th>角色</th><th>描述</th></tr>
</thead>
<tbody>
<tr><td>ADMIN</td><td th:text="${adminType}"></td></tr>
<tr><td>USER</td><td th:text="${userType}"></td></tr>
<tr><td>GUEST</td><td th:text="${guestType}"></td></tr>
<tr><td>VIP</td><td th:text="${vipType}"></td></tr>
<tr><td>MODERATOR</td><td th:text="${moderatorType}"></td></tr>
</tbody>
</table>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>This example demonstrates how to use enums together with @ConfigurationProperties to achieve type‑safe, readable, and easily maintainable configuration in a Spring Boot project.
Java Tech Enthusiast
Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.