Spring Boot 1.5+读取自定义yml配置文件

版权声明:本文为博主原创文章,未经博主允许不得转载。转载请在文章开头添加出处: https://blog.csdn.net/weixin_38676276/article/details/84956350

1、配置文件:myProps.yml

sensitiveWordPath:
  path: src/main/resources/SensitiveWord.txt

2、由于@PropertySource属性默认只用于标记并告诉spring boot加载properties类型的文件,YAML 文件不能用 @PropertySource 注解来标记加载。因此,在需要加载值的场景,需要使用属性文件。

spring boot 2.0.0.RELEASE版的文档解释如下:

24.6.4 YAML Shortcomings

YAML files cannot be loaded by using the @PropertySource annotation. 
So, in the case that you need to load values that way, you need to use a properties file.

2.1解决方法

自定义一个yaml文件加载类,并在@PropertySource注解的factory属性中声明就可以。

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

import java.io.IOException;

public class MyYmlPropertyFactory implements PropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        return name != null ? new PropertySourcesLoader().load(resource.getResource(), name, null) : new PropertySourcesLoader().load( resource.getResource(), getNameForResource(resource.getResource()), null);
    }
    private static String getNameForResource(Resource resource) {
        String name = resource.getDescription();
        if (!org.springframework.util.StringUtils.hasText(name)) {
            name = resource.getClass().getSimpleName() + "@" + System.identityHashCode(resource);
        } return name;
    }


}

2.2引入@PropertySource注解并使用

注意:必须添加@Component注解(@Component 标识为Bean

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
 * 加载yaml配置文件的方法
 * spring-boot更新到1.5.2版本后locations属性无法使用
 * @PropertySource注解只可以加载proprties文件,无法加载yaml文件
 */
@Component
@PropertySource(value = {"classpath:myProps.yml"}, factory = MyYmlPropertyFactory.class)
public class MyYml {
    

    @Value("${sensitiveWordPath.path}") //注意路径
    private String path;
    
    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }
}

3、在需要调用的配置文件内容的类中注入MyYml ,然后在需要的地方调用myYml中的getter方法


public class test{
   
    @Autowired
    privete MyYml myYml;

    //private MyYml myYml= SpringContextUtils.getBean(MyYml.class);(如果自动注入获取为null,可以尝试此方法)

//示例,不完整
public Set<String> readSensitiveWordFile() throws Exception{
	Set<String> set = null;
    //System.out.println("=============myYml="+myYml);


	File file = new File(myYml.getPath());    //读取文件,获取配置文件中的内容


	InputStreamReader read = new InputStreamReader(new FileInputStream(file),ENCODING);
	try {
		  if(file.isFile() && file.exists()){      //文件流是否存在
		  set = new HashSet<String>();
	          BufferedReader bufferedReader = new BufferedReader(read);
		  String txt = null;
		  while((txt = bufferedReader.readLine()) != null){    //读取文件,将文件内容放入到set中
		   set.add(txt);
		  }
	  }else{         //不存在抛出异常信息
		 throw new Exception("敏感词库文件不存在");
	   }
	} catch (Exception e) {
		throw e;
	}finally{
		read.close();     //关闭文件流
	}
	return set;
  }

}

猜你喜欢

转载自blog.csdn.net/weixin_38676276/article/details/84956350