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接收。
    測試
    項目結構:
    項目結構
    更多解釋可以參考這裏:一篇寫的很通俗易懂的博客
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章