SpringBoot 读取配置文件属性值

来源:互联网 发布:数据魔方架构 编辑:程序博客网 时间:2024/06/05 07:13

SpringBoot有两种配置文件properties和yml配置文件,但读取的方式都是一样的。主要有以下的两种方式,以yml文件作为讲解:
yml文件:

 auth:        authUrl: https://auth.test.com/a/        cookieName: auth.session.id        version: 1.0

1、使用@Value注解将配置文件的属性注入到类属性中

    @Value("${auth.authUrl}")    private String authUrl;    @Value("${auth.cookieName}")    private String cookieName;    @Value("${auth.redisVersion}")    private String redisVersion;

2、使用@ConfigurationProperties,它可以把同类的配置信息自动封装成实体类,在需要使用配置文件属性时,只需要将封装的实体类注入到使用出就可以获取到属性的信息。

@Component@ConfigurationProperties(prefix="auth")public class AuthSettings {    private String authUrl;    private String cookieName;    private String redisVersion;    public String getAuthUrl() {        return authUrl;    }    public void setAuthUrl(String authUrl) {        this.authUrl = authUrl;    }    public String getCookieName() {        return cookieName;    }    public void setCookieName(String cookieName) {        this.cookieName = cookieName;    }    public String getRedisVersion() {        return redisVersion;    }    public void setRedisVersion(String redisVersion) {        this.redisVersion = redisVersion;    }}
原创粉丝点击