SpringBoot读取配置文件的三种方式

167 阅读1分钟

SpringBoot读取配置文件的三种方式

application.yml 配置文件如下

image.png

1. 使用 @Value 注解

@Value("${server.port}")
private String port;

2.使用 Environment 接口

public class Test {
    
    @Autowired
    Environment env;
    
    public String getPort(){
        return env.getProperty("server.port");
    }
}

3.使用@ConfigurationProperties(prefix = "server") 注解

创建一个实体类,加上 @ConfigurationProperties(prefix = "配置文件中的属性名称") 注解和@Component 注解,在需要需要获取配置属性的类中使用 @Autowired 注入我们自定义的bean,并通过get方法后去对于的属性。

自定义的类:

@ConfigurationProperties(prefix = "server")
@Component
@Data
public class Server {
    private String port;
}

使用方法:

public class Test {

    @Autowired
    Server server;

    public String getPort(){
        return server.getPort();
    }
}