1. 程式人生 > >Springboot 之 自定義配置文件及讀取配置文件

Springboot 之 自定義配置文件及讀取配置文件

ebo hello path host 目錄 tps pre 示例 control

本文章來自【知識林】

讀取核心配置文件

核心配置文件是指在resources根目錄下的application.propertiesapplication.yml配置文件,讀取這兩個配置文件的方法有兩種,都比較簡單。

核心配置文件application.properties內容如下:

server.port=9090

test.msg=Hello World Springboot!
  • 使用@Value方式(常用):
@RestController
public class WebController {

    @Value("${test.msg}")
    private String msg;

    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String index() {
        return "The Way 1 : " +msg;
    }
}

註意:@Value的${}中包含的是核心配置文件中的鍵名。在Controller類上加@RestController表示將此類中的所有視圖都以JSON方式顯示,類似於在視圖方法上加@ResponseBody

訪問:http://localhost:9090/index 時將得到The Way 1 : Hello World Springboot!

  • 使用Environment方式
@RestController
public class WebController {

    @Autowired
    private Environment env;

    @RequestMapping(value = "index2", method = RequestMethod.GET)
    public String index2() {

        return "The Way 2 : " + env.getProperty("test.msg");
    }
}

註意:這種方式是依賴註入Evnironment來完成,在創建的成員變量private Environment env上加上@Autowired註解即可完成依賴註入,然後使用env.getProperty("鍵名")即可讀取出對應的值。

訪問:http://localhost:9090/index2 時將得到The Way 2 : Hello World Springboot!


讀取自定義配置文件

為了不破壞核心文件的原生態,但又需要有自定義的配置信息存在,一般情況下會選擇自定義配置文件來放這些自定義信息,這裏在resources/config目錄下創建配置文件my-web.properties

resources/config/my-web.properties

內容如下:

web.name=zslin
web.version=V 1.0
web.author=[email protected]

創建管理配置的實體類:

@ConfigurationProperties(locations = "classpath:config/my-web.properties", prefix = "web")
@Component
public class MyWebConfig {

    private String name;

    private String version;

    private String author;

    public String getAuthor() {
        return author;
    }

    public String getName() {
        return name;
    }

    public String getVersion() {
        return version;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setVersion(String version) {
        this.version = version;
    }
}

註意:

  • @ConfigurationProperties註釋中有兩個屬性:

    • locations:指定配置文件的所在位置
    • prefix:指定配置文件中鍵名稱的前綴(我這裏配置文件中所有鍵名都是以web.開頭)
  • 使用@Component是讓該類能夠在其他地方被依賴使用,即使用@Autowired註釋來創建實例。

創建測試Controller

@RestController
@RequestMapping(value = "config")
public class ConfigController {

    @Autowired
    private MyWebConfig myWebConfig;

    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String index() {
        return "webName: "+myWebConfig.getName()+", webVersion: "+
                myWebConfig.getVersion()+", webAuthor: "+myWebConfig.getAuthor();
    }
}

註意:由於在MyWebConfig類上加了註釋@Component,所以可以直接在這裏使用@Autowired來創建其實例對象。

訪問:http://localhost:9090/config/index 時將得到webName: zslin, webVersion: V 1.0, webAuthor: [email protected]

示例代碼:https://github.com/zsl131/spring-boot-test/tree/master/study02

本文章來自【知識林】

Springboot 之 自定義配置文件及讀取配置文件