1. 程式人生 > >springBoot使用Controller讀取配置檔案兩種方式&讀取自定義配置方法

springBoot使用Controller讀取配置檔案兩種方式&讀取自定義配置方法

Controller

核心配置檔案
    application.propertie
web.msg=Hello! This is Controller demo;
Controller:
@RestController
public class WebController {
    //使用value注入
    @Value("${web.msg}")
    private String msg;

    @RequestMapping("index")
    public String index() {
        System.out.println(msg);
        return
"The No1 :" + msg; } @Autowired private Environment env; @RequestMapping("index2") public String index2() { System.out.println(env.getProperty("web.msg")); return "The No2 :"+ env.getProperty("web.msg"); } }

讀取自定義配置方法

自定義配置檔案
web.name=zpeng
web.version=V 1.0
web.author=777423444@qq.com web.title=Springboot-自定義配置檔案 讀取配置檔案封裝成實體類 package cn.xilin.config; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; /** * @Author : zpeng * @description : * @Date : Create in 2018/1/2 22:59 * cn.xilin.config */
@Component @ConfigurationProperties(locations = "classpath:config/my-web.properties", prefix = "web") public class MyWebConfig { private String name; private String version; private String author; private String title; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
Controller測試

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

    @Autowired
    private MyWebConfig myWebConfig;

    @RequestMapping("index")
    public String index() {
        return "webName:"+myWebConfig.getName()+"=====webVersion:"+myWebConfig.getVersion()+"=====webAuthor:"+myWebConfig.getAuthor()+"=====webTitle:"+myWebConfig.getTitle();
    }
}

相關推薦

no