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();
    }
}

猜你喜欢

转载自blog.csdn.net/Strugglein/article/details/78956941