SpringBoot properties和yml配置文件的设置与读取

本文详细介绍了SpringBoot2.x中配置文件的设置,包括自定义参数的声明与引用,随机数的生成,以及数组和Map配置的使用方法。同时,讲解了如何通过@Value和@ConfigurationProperties注解来读取配置文件中的信息,包括普通信息、数组、List和Map数据结构的读取示例。
摘要由CSDN通过智能技术生成

参考资料

  1. Spring Boot 2.x基础教程:配置文件详解


一. 设置配置文件

1.1 自定义参数

.properties配置文件

# 自定义参数
project-user.name: jiafeitian

# 自定义参数的引用,直接通过${}引用配置信息
project-admin.name: ${project-user.name}

.yml配置文件

project-user:
  name: jiafeitian
project-admin:
  name: ${project-user.name}

1.2 随机数生成

在一些特殊情况下,有些参数我们希望它每次加载的时候不是一个固定的值,比如:密钥、服务端口等。

在Spring Boot的属性配置文件中,我们可以通过使用${random}配置来产生随机的int值、long值或者string字符串,这样我们就可以容易的通过配置来属性的随机生成,而不是在程序中通过编码来实现这些逻辑。

.properties配置文件

# 随机字符串
com.jmw.blog.random-str = ${random.value}

# 随机int
com.jmw.blog.random-int = ${random.int}

# 随机long
com.jmw.blog.random-long = ${random.long}

# 10以内的随机数
com.jmw.blog.random-0-10 = ${random.int(10)}

# 10-20的随机数
com.jmw.blog.random-10-20 = ${random.int[10,20]}

.yml配置文件

com:
  jmw:
    blog:
      random-0-10: ${random.int(10)}
      random-10-20: ${random.int[10,20]}
      random-int: ${random.int}
      random-long: ${random.long}
      random-str: ${random.value}

1.3 数组配置

.properties配置文件

  • 通过逗号进行分隔
com.jmw.address = china01,china02,china03
com.jmw.hobby = eat,sleep,study

.yml配置文件

  • 通过逗号进行分隔
com:
  jmw:
    address: china01,china02,china03
    hobby: eat,sleep,study

1.4 Map配置

.properties配置文件

  • 方式1: 直接写配置对象
com.jmw.info = {id: "110120", sex: "man"}
  • 方式2: ❗方式2主要通过获取信息的时候,将其转换为Map
com.jmw.device.pc=111
com.jmw.device.app=222
com.jmw.device.weichat=333

.yml配置文件

  • 方式1
com:
  jmw:
    info: '{id: "110120", sex: "man"}'
  • 方式2
com:
  jmw:
    device:
      app: 222
      pc: 111
      weichat: 333

二. 读取配置文件

  • 读取配置文件分为@value注解手动读取和@ConfigurationProperties注解自动读取两种方式。
  • @ConfigurationProperties注解自动读取的话,如果不使用@Configuration注解将其放入Spring的IOC容器中的话,需要配合@EnableConfigurationProperties注解使用,详情可参照 2.3 章节

2.1 普通信息的读取

⏹通过@Value注解实现

import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import lombok.Getter;

@Getter
@Configuration
public class ProjectConfig1 {
	
	@Value("${project-user.name}")
    private String projectUserName;
	
	@Value("${project-admin.name}")
    private String projectAdminName;
	
	@Value("${com.jmw.blog.random-str}")
    private String randomStr;
	
	@Value("${com.jmw.blog.random-int}")
    private String randomInt;
	
	@Value("${com.jmw.blog.random-long}")
    private String randomLong;
	
	@Value("${com.jmw.blog.random-0-10}")
    private String random0And10;
	
	@Value("${com.jmw.blog.random-10-20}")
    private String random10ANd20;
}

👇👇👇效果

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Controller;

@Controller
public class J002ConfigTest implements CommandLineRunner {
	
	@Autowired
	private ProjectConfig1 config1;

	@Override
	public void run(String... args) throws Exception {
		
		// 获取自定义的配置信息
		System.out.println(config1.getProjectUserName());
		// 自定义配置信息中的参数引用
		System.out.println(config1.getProjectAdminName());
		
		/*
		 * 获取配置文件中的随机数
		 */
		// 获取随机字符串
		System.out.println(config1.getRandomStr());  // f6fdbef8bb19e7ff5cba83b04ba8b414
		// 获取随机int
		System.out.println(config1.getRandomInt());  // -423013463
		// 获取随机long
		System.out.println(config1.getRandomLong());  // 8471851910099450609
		// 获取0到10之间的随机数
		System.out.println(config1.getRandom0And10());  // 6
		// 获取10到20之间的随机数
		System.out.println(config1.getRandom10ANd20());  // 17
	}
}

2.2 数组信息的读取

⏹@Value注解

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@Configuration
public class ProjectConfig1 {
	
	// 读取配置文件中的数组
	@Value("${com.jmw.address}")
	private String[] address;
}

⏹@ConfigurationProperties注解自动装配

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix = "com.jmw")
public class ProjectConfig2 {
	
	// 自动创配为Array
	private String[] address;    
}

👇👇👇获取

@Controller
public class J002ConfigTest implements CommandLineRunner {
	
	@Autowired
	private ProjectConfig1 config1;
	
	@Autowired
	private ProjectConfig2 config2;

	@Override
	public void run(String... args) throws Exception {
		
		// 获取配置文件中的Array
		String[] address = config1.getAddress();
		System.out.println(Arrays.toString(address));  // [china01, china02, china03]
		System.out.println(Arrays.toString(config2.getAddress()));  // [china01, china02, china03]
	}
}

2.3 List信息的读取

⏹@Value注解

import java.util.List;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@Configuration
public class ProjectConfig1 {
	
	// 读取配置文件中的数组,使用SpEL表达式将其转换为List
	@Value("#{'${com.jmw.hobby}'.split(',')}")
	private List<String> hobby;
}

⏹@ConfigurationProperties注解自动装配

  • 注意,此时的配置文件并没有添加到Spring的IOC容器中
  • 需要使用该配置文件的时候,需要配合@EnableConfigurationProperties注解使用
import java.util.List;

import org.springframework.boot.context.properties.ConfigurationProperties;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@ConfigurationProperties(prefix = "com.jmw")
public class ProjectConfig2 {
	
	// 自动创配值List
	private List<String> hobby;
}

👇👇👇获取

  • 因为ProjectConfig2配置文件并没有在Spring的IOC容器中,所以必须使用EnableConfigurationProperties注解开启后才能注入使用,否则会报错。
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Controller;
import org.springframework.boot.CommandLineRunner;

@Controller
@EnableConfigurationProperties(ProjectConfig2.class)
public class J002ConfigTest implements CommandLineRunner {
	
	@Autowired
	private ProjectConfig1 config1;
	
	@Autowired
	private ProjectConfig2 config2;

	@Override
	public void run(String... args) throws Exception {
		
		// 获取配置文件中的List
		List<String> hobby = config1.getHobby();
		System.out.println(hobby);  // [eat, sleep, study]
		System.out.println(config2.getHobby());  // [eat, sleep, study]
	}
}

2.4 Map信息的读取

  • @Value注解需要配合SpEL表达式(#{…})来获取,
    且只能获取{id: "110120", sex: "man"}样式的数据
  • @ConfigurationProperties注解自动装配无法获取{id: "110120", sex: "man"}样式的数据,只能自动装配com.jmw.device.pc这种层次的数据。

⏹@Value注解

import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@Configuration
public class ProjectConfig1 {
	
	// 读取Map的配置,需要使用SpEL表达式(#{...})
	@Value("#{${com.jmw.info}}")
	private Map<String,String> infoMap;
}

⏹@ConfigurationProperties注解自动装配

import java.util.Map;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix = "com.jmw")
public class ProjectConfig2 {
	
	/**
	 * 通过@ConfigurationProperties注解自动完成Map的配置
	 * 属性的名称一定要和配置文件中的保持一致,否则无法自动完成装配 
	 */
	private Map<String,String> device;
}

👇👇👇获取

@Controller
public class J002ConfigTest implements CommandLineRunner {
	
	@Autowired
	private ProjectConfig1 config1;
	
	@Autowired
	private ProjectConfig2 config2;

	@Override
	public void run(String... args) throws Exception {
		
		// 获取配置文件中的Map
		Map<String,String> infoMap = config1.getInfoMap();
		System.out.println(infoMap);  // {id=110120, sex=man}
		System.out.println(config2.getDevice());  // {app=222, pc=111, weichat=333}
	}
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 项目中,读取 YAML 配置文件的方式与读取 properties 配置文件的方式类似。可以使用 `@ConfigurationProperties` 注解将配置文件中的属性与 Java 对象绑定起来,也可以使用 `@Value` 注解逐个读取配置。 以下是使用 `@ConfigurationProperties` 注解读取 YAML 配置文件的示例代码: 1. 创建一个 Java 类,用于存储 YAML 配置文件中的属性: ```java @ConfigurationProperties(prefix = "example") public class ExampleProperties { private String name; private int age; //其他属性... //getter和setter方法... } ``` 2. 在 YAML 配置文件中定义属性: ```yaml example: name: "Tom" age: 18 #其他属性... ``` 3. 在 Spring Boot 应用程序的配置类中,启用 `@EnableConfigurationProperties` 注解,并将 `ExampleProperties` 类加入到 Spring 容器中: ```java @EnableConfigurationProperties(ExampleProperties.class) @Configuration public class AppConfig { @Bean public ExampleProperties exampleProperties() { return new ExampleProperties(); } } ``` 4. 在需要读取配置的地方,注入 `ExampleProperties` 对象即可使用: ```java @RestController public class ExampleController { @Autowired private ExampleProperties exampleProperties; @GetMapping("/example") public ExampleProperties getExample() { return exampleProperties; } } ``` 以上示例代码使用了 `@ConfigurationProperties` 注解将 YAML 配置文件中的属性与 `ExampleProperties` 类绑定起来,并在 Spring Boot 应用程序的配置类中将 `ExampleProperties` 类加入到 Spring 容器中。在需要读取配置的地方,使用 `@Autowired` 注解注入 `ExampleProperties` 对象即可使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值