Skip to content

读取yml、properties配置文件里的属性值

特点

配置文件具有以下特点:

一、配置文件具有集中性

二、配置文件清晰,没有业务逻辑干扰

在实际项目中,我们会把经常改变的属性抽取出来,放到配置文件里,比如数据库、JPA、redis等配置

使用方法

@Value方式(常用)

语法:

@Value("${配置文件中的key:默认值}")
@Value("${配置文件中的key}")

备注

@Value注解推荐引入application.yml这种配置文件里的数据(不需要做任何处理)

如果引入自定义的properties文件里的数据,需要在入口文件里使用@PropertySource注解进行配置

java
@SpringBootApplication
@PropertySource(value = "classpath:config/test.properties")
public class MisszbApplication {

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

}

方法一:在类文件里定义变量,将配置文件中的值引入(这种是直接使用)

java
@Service
public class OrderServiceImpl implements OrderService {
   
   @Value("${misszb.order.max-sku-limit}")
   private int maxSkuLimit;
}

方法二:自定义配置文件(需要对数据进行二次处理)

java
@Configuration(proxyBeanMethods = false)
@Slf4j
public class WebConfiguration implements WebMvcConfigurer {

    @Value("${auth.enabled:false}")
    private boolean authEnabled;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        if (authEnabled) {
            //开发环境忽略签名认证
            registry.addInterceptor(authorizeInterceptor)
                    .excludePathPatterns(getDirServePath());
        }
        if (requestLogEnabled) {
            registry.addInterceptor(requestLogInterceptor);
        }
        registry.addInterceptor(logInterceptor);
    }

}

使用@ConfigurationProperties方式

项目地址:misscmszb项目下的fileUploadDev分支中的FileConfiguration文件

备注

这种方式常用在引入自定义的配置文件,就是非application.yml这种文件

一、需要使用@PropertySource注解指定配置的文件

二、如果配置文件是properties,那只指定文件就可以,如果是yml文件,还需要指定factory

方法一:在一个配置类里读取配置文件的值

备注

这种写法需要用到@EnableConfigurationProperties注解,作用是使 使用 @ConfigurationProperties 注解的类生效。

如果一个配置类只配置@ConfigurationProperties注解,而没有使用@Component或者实现了@Component的其他注解,那么在IOC容器中是获取不到properties 配置文件转化的bean。说白了 @EnableConfigurationProperties 相当于把使用 @ConfigurationProperties 的类进行了一次注入。

简单点说@EnableConfigurationProperties的功能类似于@Component。

FileConfiguration.java

java
package com.zb.misscmszb.module.file;

import com.zb.misscmszb.common.factory.YamlPropertySourceFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

/**
 * 文件配置类
 */
@Configuration
@ConfigurationProperties(prefix = "cms.file")
@PropertySource(
        value = "classpath:com/zb/misscmszb/extension/file/config.yml",
        encoding = "UTF-8", factory = YamlPropertySourceFactory.class)
public class FileConfiguration {
    private static final String[] DEFAULT_EMPTY_ARRAY = new String[0];

    private String storeDir = "/assets";

    private String singleLimit = "2MB";

    private Integer nums = 10;

    private String domain;

    private String[] exclude = DEFAULT_EMPTY_ARRAY;

    private String[] include = DEFAULT_EMPTY_ARRAY;

    /**
     * 文件存储路径
     */
    private String servePath = "assets/**";

    public String getServePath() {
        return servePath;
    }

    public void setServePath(String servePath) {
        this.servePath = servePath;
    }

    public String getStoreDir() {
        return storeDir;
    }

    public void setStoreDir(String storeDir) {
        this.storeDir = storeDir;
    }

    public String getSingleLimit() {
        return singleLimit;
    }

    public void setSingleLimit(String singleLimit) {
        this.singleLimit = singleLimit;
    }

    public Integer getNums() {
        return nums;
    }

    public void setNums(Integer nums) {
        this.nums = nums;
    }

    public String[] getExclude() {
        return exclude;
    }

    public void setExclude(String[] exclude) {
        this.exclude = exclude;
    }

    public String[] getInclude() {
        return include;
    }

    public void setInclude(String[] include) {
        this.include = include;
    }

    public String getDomain() {
        return domain;
    }

    public void setDomain(String domain) {
        this.domain = domain;
    }
}

YamlPropertySourceFactory.java

java
package com.zb.misscmszb.common.factory;

import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;

import java.io.IOException;
import java.util.List;

public class YamlPropertySourceFactory implements PropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        List<PropertySource<?>> sources = new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource());
        return sources.get(0);
    }
}

方法二:将配置类进行拆分(这是为了对数据进行二次处理)

项目地址:misscmszb

application.yml

yml
zb:
  cms:
    # 开启行为日志记录(logger)
    logger-enabled: true
    # access token 过期时间,3600s 一个小时
    token-access-expire: 3600
    # refresh token 过期时间,2592000s 一个月
    token-refresh-expire: 2592000
    # 令牌 secret
    token-secret: x88Wf0991079889x8796a0Ac68f9ecJJU17c5Vbe8beod7d8d3e695*4

CmsProperties.java 将application.yml配置文件里的值和定义的变量绑定

java
package com.zb.misscmszb.common.configuration;

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

/**
 * cms 配置属性
 */
@ConfigurationProperties(prefix = "zb.cms")
public class CmsProperties {

    private static final String[] DEFAULT_EXCLUDE_METHODS = new String[]{"OPTIONS"};
    private String tokenSecret = "";

    private String[] excludeMethods = DEFAULT_EXCLUDE_METHODS;

    private Long tokenAccessExpire = 3600L;

    private Long tokenRefreshExpire = 2592000L;

    public String getTokenSecret() {
        return tokenSecret;
    }

    public void setTokenSecret(String tokenSecret) {
        this.tokenSecret = tokenSecret;
    }

    public Long getTokenAccessExpire() {
        return tokenAccessExpire;
    }

    /**
     * 设置 access token 过期时间
     *
     * @param tokenAccessExpire 过期时间
     */
    public void setTokenAccessExpire(Long tokenAccessExpire) {
        this.tokenAccessExpire = tokenAccessExpire;
    }

    public Long getTokenRefreshExpire() {
        return tokenRefreshExpire;
    }

    /**
     * 设置 refresh token 过期时间
     *
     * @param tokenRefreshExpire 过期时间
     */
    public void setTokenRefreshExpire(Long tokenRefreshExpire) {
        this.tokenRefreshExpire = tokenRefreshExpire;
    }

    public String[] getExcludeMethods() {
        return excludeMethods;
    }

    public void setExcludeMethods(String[] excludeMethods) {
        this.excludeMethods = excludeMethods;
    }
}

CmsConfiguration.java 配置文件,通过@EnableConfigurationProperties注解和CmsProperties绑定

java
package com.zb.misscmszb.common.configuration;

import com.zb.misscmszb.extension.token.DoubleJWT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * cms配置文件
 */
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(CmsProperties.class)
public class CmsConfiguration {

    @Autowired
    private CmsProperties properties;

    // 调用DoubleJWT的构造函数,生成DoubleJWT对象,并通过@Bean注解注入到容器里
    @Bean
    public DoubleJWT jwt() {
        String secret = properties.getTokenSecret();
        Long accessExpire = properties.getTokenAccessExpire();
        Long refreshExpire = properties.getTokenRefreshExpire();

        if (accessExpire == null) {
            accessExpire = 60 * 60L;
        }

        if (refreshExpire == null) {
            // 一个月
            refreshExpire = 60 * 60 * 24 * 30L;
        }

        return new DoubleJWT(secret, accessExpire, refreshExpire);
    }
}

如有转载或 CV 的请标注本站原文地址