【SpringBoot】SpringBoot 读取配置文件中的自定义属性的 5 种方法

时间:2025-02-13 09:04:02

SpringBoot 配置文件的格式有两种:yml、properties。有些方法都适用,但有些方法就有针对性了。

概括地说,Spring Boot 中读取配置文件有以下 5 种方法:

  1. 使用 @Value 读取配置文件(yml、properties)
  2. 使用 @ConfigurationProperties 读取配置文件(yml、properties)
  3. 使用 Environment 读取配置文件(yml、properties)
  4. 使用 @PropertySource 读取配置文件(yml、properties)
  5. 使用 原生方式 读取配置文件(properties)

如:配置文件内容:

yml 格式:

file:
  uploadPath: E:/upload

properites 格式:

=E:/upload

1、 使用 @Value 读取配置文件

@SpringBootApplication
public class Application implements InitializingBean{

	@Value("${}")
	private String profileName;

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.println(profileName);
	}
}

2、使用 @ConfigurationProperties 读取配置文件

@Data
@Component
@ConfigurationProperties(prefix = "file")
public class FileConfig {
    // 上传路径
    private String uploadPath;
}

3、使用 Environment 读取配置文件

将此类使用 @Autowired 注入到类中就可以使用它的 getProperty() 方法来获取某个配置项的值了

@SpringBootApplication
public class Application implements InitializingBean{

	@Autowired
	private Environment environment;

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.println(environment.getProperty(""));
	}
}

4、使用 @PropertySource 读取配置文件
使用 @PropertySource 注解可以用来指定读取某个配置文件,比如指定读取 配置文件的配置内容

@SpringBootApplication
@PropertySource("classpath:")
public class Application implements InitializingBean{

	@Value("${}")
	private String path;

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.println(path);
	}
}

5、使用 原生方式 读取配置文件(properties)

就是使用 Properites 对象读取。