1. 程式人生 > >SpringBoot的自定義配置方法一,通過自定義配置檔案

SpringBoot的自定義配置方法一,通過自定義配置檔案

 

自定義配置的目的:通過自定義屬性,注入到程式中使用,可以靈活的更改配置資訊,修改自定義屬性值,達到修改程式的目的。

一、新建一個SpringBoot工程,目錄結構如下:

  其中MyConfig.java檔案內容為:@Component與@ConfigurationProperties(prefix="winson")註解的使用

package cn.com.winson.springboot.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component; /** * 自定義配置類 * * @author lvhao * @date 2018年12月7日 * @time 下午8:05:43 */ /*@Component註解:通過此註解,該類成為Spring的bean,方便注入到其它類中使用*/ /*@ConfigurationProperties註解:宣告此類為一個自定義配置屬性類,prefix為屬性的字首*/ @Component @ConfigurationProperties(prefix="winson") public class MyConfig {
private Integer age; private String name; public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } }

IndexController.java檔案中的內容為:注入自定義配置類

package cn.com.winson.springboot.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.winson.springboot.config.MyConfig;

@Controller
public class IndexController {
    
    /*注入自定義配置類的bean*/
    @Autowired
    private MyConfig myConfig;
    
    /*新增@ResponseBody註解與返回值型別String組合使用,返回的是json字串,而不是頁面*/
    @GetMapping("/getInfo")
    @ResponseBody
    public String getInfo() {
        return "自定義屬性的age為:" + myConfig.getAge() + ";name為:" + myConfig.getName() + "";
    }

}

 最重要的核心配置檔案application.properties檔案內容為:宣告屬性和值

#自定義屬性
winson.age=20
winson.name=winson

執行啟動類,訪問結果為:

    總結:以上就是通過自定義配置類來實現自定義屬性的步驟,程式碼可以直接複用。還有一種自定義配置的方式是通過@Value註解,直接在使用的時候,注入到程式中就可以使用,該方法見下篇講解。