Configure the dictionary data in the yml file, and load the data into the Map by loading the yml
The yml configuration in Spring Boot refers to the configuration in other yml. # Create a new application-xxx
in the configuration file directory (such as resources). The yml file must start with application. Multiple files are separated by "," and cannot be newline
Project structure file
application.yml
server: port: 8088 application: name: VipSoft Env Demo spring: profiles: include: dic # 在配置文件目录(如:resources)下新建application-xxx 开头的yml文件, 多个文件用 "," 号分隔,不能换行 #性别字典 user-gender: 0: 未知 1: 男 2: 女
application-dic.yml
Change the dictionary Independently into a separate yml file
#支付方式 pay-type: 1: 微信支付 2: 货到付款
In the resources
directory, create the META-INF
directory and create the spring.factories
file,
Spring Factories is a mechanism similar to Java SPI. It configures the implementation class name of the interface in the META-INF/spring.factories file, and then reads these configuration files and instantiates them in the program.
The content is as follows:
# Environment Post Processor org.springframework.boot.env.EnvironmentPostProcessor=com.vipsoft.web.utils.ConfigUtil
ConfigUtil
package com.vipsoft.web.utils; import org.springframework.boot.SpringApplication; import org.springframework.boot.context.properties.bind.BindResult; import org.springframework.boot.context.properties.bind.Binder; import org.springframework.boot.env.EnvironmentPostProcessor; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.PropertySource; import org.springframework.util.Assert; public class ConfigUtil implements EnvironmentPostProcessor { private static Binder binder; private static ConfigurableEnvironment environment; public static String getString(String key) { Assert.notNull(environment, "environment 还未初始化!"); return environment.getProperty(key, String.class, ""); } public static <T> T bindProperties(String prefix, Class<T> clazz) { Assert.notNull(prefix, "prefix 不能为空"); Assert.notNull(clazz, "class 不能为空"); BindResult<T> result = ConfigUtil.binder.bind(prefix, clazz); return result.isBound() ? result.get() : null; } /** * 通过 META-INF/spring.factories,触发该方法的执行,进行环境变量的加载 */ @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { for (PropertySource<?> propertySource : environment.getPropertySources()) { if (propertySource.getName().equals("refreshArgs")) { return; } } ConfigUtil.environment = environment; ConfigUtil.binder = Binder.get(environment); } }
DictVo
package com.vipsoft.web.vo; public class DictVO implements java.io.Serializable { private static final long serialVersionUID = 379963436836338904L; /** * 字典类型 */ private String type; /** * 字典编码 */ private String code; /** * 字典值 */ private String value; public DictVO(String code, String value) { this.code = code; this.value = value; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
DefaultController
package com.vipsoft.web.controller; import com.vipsoft.web.utils.ConfigUtil; import com.vipsoft.web.vo.DictVO; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; @RestController public class DefaultController { @GetMapping(value = "/") public String login() { return "VipSoft Demo !!!"; } @GetMapping("/list/{type}") public List<DictVO> listDic(@PathVariable("type") String type) { LinkedHashMap dict = ConfigUtil.bindProperties(type.replaceAll("_", "-"), LinkedHashMap.class); List<DictVO> list = new ArrayList<>(); if (dict == null || dict.isEmpty()) { return list; } dict.forEach((key, value) -> list.add(new DictVO(key.toString(), value.toString()))); return list; } }
Running effect
Unit Test
package com.vipsoft.web; import com.vipsoft.web.controller.DefaultController; import com.vipsoft.web.utils.ConfigUtil; import com.vipsoft.web.vo.DictVO; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.List; @SpringBootTest public class DicTest { @Autowired DefaultController defaultController; @Test public void DicListTest() throws Exception { List<DictVO> pay_type = defaultController.listDic("pay-type"); pay_type.forEach(p -> System.out.println(p.getCode() + " => " + p.getValue())); List<DictVO> user_gender = defaultController.listDic("user-gender"); user_gender.forEach(p -> System.out.println(p.getCode() + " => " + p.getValue())); } @Test public void getString() throws Exception { String includeYml = ConfigUtil.getString("spring.profiles.include"); System.out.println("application 引用了配置文件 =》 " + includeYml); } }
The above is the detailed content of How does SpringBoot load dictionary data in yml files?. For more information, please follow other related articles on the PHP Chinese website!

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version
Visual web development tools