Springboot 之 自定义配置文件及读取配置文件

本文章来自【知识林】java

读取核心配置文件

核心配置文件是指在resources根目录下的application.propertiesapplication.yml配置文件,读取这两个配置文件的方法有两种,都比较简单。git

核心配置文件application.properties内容以下:github

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方式显示,相似于在视图方法上加@ResponseBodyweb

访问:http://localhost:9090/index 时将获得The Way 1 : Hello World Springboot!spring

  • 使用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("键名")便可读取出对应的值。bash

访问:http://localhost:9090/index2 时将获得The Way 2 : Hello World Springboot!app


读取自定义配置文件

为了避免破坏核心文件的原生态,但又须要有自定义的配置信息存在,通常状况下会选择自定义配置文件来放这些自定义信息,这里在resources/config目录下建立配置文件my-web.propertiessvg

resources/config/my-web.properties内容以下:spring-boot

web.name=zslin
web.version=V 1.0
web.author=393156105@qq.com

建立管理配置的实体类:

@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: 393156105@qq.com

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

本文章来自【知识林】