1. 程式人生 > 其它 >使用@Value註解獲取yml配置檔案中的自定義屬性(三種不同環境下詳細獲取方式:變數+靜態變數+靜態程式碼塊)

使用@Value註解獲取yml配置檔案中的自定義屬性(三種不同環境下詳細獲取方式:變數+靜態變數+靜態程式碼塊)

技術標籤:Java後臺java讀取配置檔案自定義屬性

文章目錄


一。配置檔案說明

1.application.yml配置:(這裡使用的是application-local.yml配置檔案)

在這裡插入圖片描述

2.application-local.yml自定義屬性配置:

在這裡插入圖片描述

二。變數屬性獲取

  @Value("${fastdfs_config.path}")
  private String path;

三。靜態變數獲取

1.第一種方式:

    //fastdfs配置檔案所在路徑
    private
static String filePath; @Value("${fastdfs_config.path}") public void setFilePath(String path){ this.filePath=path; }

2.第二種方式:

    @Value("${fastdfs_config.path}")
    private String path;
    
    @PostConstruct
    public void setPath(String path){
        this
.filePath=path; }

四。靜態程式碼塊獲取


static {
        try {
            //獲取配置檔案中自定義的fastdfs_config.path值
            String filePath=(String)getCommonYml("fastdfs_config.path");
            ClientGlobal.init(filePath);
        } catch (IOException e) {
            logger.error("Get FastDFS config file fail!"
,e); } catch (MyException e) { logger.error("FastDF init fail!",e); } } //獲取application-local.yml檔案中的屬性配置 public static Object getCommonYml(Object key){ Resource resource = new ClassPathResource("/application-local.yml"); Properties properties = null; try { YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean(); yamlFactory.setResources(resource); properties = yamlFactory.getObject(); } catch (Exception e) { e.printStackTrace(); return null; } return properties.get(key); }

特別注意的是:需要與@Component、@Service等Spring註解配合開啟!!!