SpringBoot读取resources下的自定义yaml文件(配置只需两步)

SpringBoot读取resources下的自定义yaml文件


permission.yml文件内容:

uri:

  // 数组
  admin:
    - /v1/mytoken/picture
    - /v1/
    
  // string字符串
  test: test
  1. 通过PropertySourcePlaceholderConfigurer来加载yml文件,暴露yml文件到spring environment
// 加载YML格式自定义配置文件
	@Bean
	public static PropertySourcesPlaceholderConfigurer properties() {
		PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
		YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
//		yaml.setResources(new FileSystemResource(ResourceUtils.CLASSPATH_URL_PREFIX + "permission.yml"));//File引入
		yaml.setResources(new ClassPathResource("permission.yml"));//class引入,避免了路径处理问题
		configurer.setProperties(yaml.getObject());
		return configurer;
	}

注:这块代码可以直接放在启动类下,或者新建一个类配合@Configuration使用,@Bean的使用方法可以参考我之前写的博客:Springboot之@Bean和@Configuration的简单使用

  1. 编写一个model与yaml的映射,可以直接通过 类.属性 的方式去调用yaml
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.List;

@Data
@Component
@ConfigurationProperties(prefix = "uri")
public class Permission {

   // 这里不需要 @Value
   private List<String> admin;
   private String test;

}

配置完毕,以下为调用及测试内容:

  1. 通过注入的方式调用
import com.eyuai.eyuaiCMS.model.common.Permission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

   @Autowired
   private Permission permission;

   @GetMapping("/test")
   public Permission test(){
       return permission;
   }
}
  1. 测试结果:前面加了 “-”的是数组,可以直接用list接收。
    测试
    项目结构:
    项目结构
    更多解释可以参考这里:一篇写的很通俗易懂的博客
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章