1. 程式人生 > 其它 >關於springboot專案讀取 .yml 配置檔案的方法

關於springboot專案讀取 .yml 配置檔案的方法

application.yml

# 系統配置
server:
  # 伺服器的HTTP埠,預設為8080
  port: 9006
  servlet:
    # 應用的訪問路徑
    context-path: /

# 自定義配置
url:
  ip: 127.0.0.1
  port: 8080
  protocol: http
configs:
  str: test
  map:
    id: 0125
    name: name
    code: code
  list:
    - testStr1
    - testStr2
    - testStr3
  listMap:
    - id: 10235
      name: name1
    - id: 20357
      name: name2
    - id: 30568
      name: name3
View Code

方法一:

使用@ConfigurationProperties(prefix = "configs") 可以以string,map,list等資料型別返回配置資訊:

SysConfigs.java:

package com.example.demo.common;

import lombok.Data;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.List; import java.util.Map; @Data @ToString @Component @ConfigurationProperties(prefix = "configs") public class SysConfigs { /** String型別 **/ private String str; /** map型別 **/ private Map<String, String> map; /** list **/ private List<String> list;
/** list **/ private List<Map<String, String>> listMap; }
View Code

方法二:

在使用@Component,@service,@RestController,@Controller 等註解的java類中的屬性上使用@Value("${url.ip}")進行配置讀取:

ConfigsController.java:

package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.common.SysConfigs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("configs")
public class ConfigsController {

    @Value("${url.ip}")
    private String ip;

    @Value("${url.port}")
    private String port;

    @Value("${url.protocol}")
    private String protocol;

    @Autowired
    private SysConfigs sysConfigs;

    @GetMapping("get-all")
    public ResponseEntity<JSONObject> getAll() {
        JSONObject json = new JSONObject();
        json.put("str", sysConfigs.getStr());
        json.put("map", sysConfigs.getMap());
        json.put("list", sysConfigs.getList());
        json.put("listMap", sysConfigs.getListMap());
        json.put("url", protocol + "://" + ip + ":" + port);
        return ResponseEntity.ok().body(json);
    }
}
View Code

最終效果:

細心的你可能會發現,在SysConfigs.java中多了兩個註解@Data@ToString,而且並沒有寫getter和setter方法,這是因為在idea中安裝了lombok,只需要關心有哪些屬性就行,可以在開發中省好多事兒。

每天進步一點點,點滴記錄,積少成多。

以此做個記錄,

如有不足之處還望多多留言指教!