SpringBoot 读取配置文件主要有以下四种方式:
- 使用 
@Value注解 
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
 
@Component
public class MyBean {
 
    @Value("${my.property}")
    private String myProperty;
 
    // getter and setter
}- 使用 
@ConfigurationProperties注解 
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
 
@Component
@ConfigurationProperties(prefix = "my")
public class MyProperties {
 
    private String property;
 
    // getter and setter
}- 使用 
Environment接口 
import org.springframework.core.env.Environment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
@Component
public class MyEnvironment {
 
    private Environment environment;
 
    @Autowired
    public MyEnvironment(Environment environment) {
        this.environment = environment;
    }
 
    public String getMyProperty() {
        return environment.getProperty("my.property");
    }
}- 使用 
PropertiesLoaderUtils工具类 
import org.springframework.core.io.support.PropertiesLoaderUtils;
import java.io.IOException;
import java.util.Properties;
 
public class MyPropertiesLoader {
 
    public Properties loadProperties() throws IOException {
        return PropertiesLoaderUtils.loadAllProperties("myProperties");
    }
}在这四种方法中,@Value 注解用于注入简单配置值,适用于少量配置的场景。@ConfigurationProperties 注解用于创建配置类,适用于有层次结构的配置。Environment 接口提供了访问运行时环境中的属性的方法,可以用来读取任何配置属性。PropertiesLoaderUtils 工具类用于加载指定的配置文件,可以读取自定义的配置文件。