Springboot读取定义配置⽂件的⼏种⽅法
⼀、读取核⼼配置⽂件
  核⼼配置⽂件是指在resources根⽬录下的application.properties或l配置⽂件,读取这两个配置⽂件的⽅法有两种,都⽐较简单。
  核⼼配置⽂件application.properties内容如下:
server.port=9090
test.msg=Hello World Springboot!对冲外汇
1、使⽤@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。
2、使⽤Environment⽅式
@RestController
public class WebController {
@Autowired
private Environment env;
@RequestMapping(value = "index2", method = RequestMethod.GET)
public String index2() {
return"The Way 2 : " + Property("test.msg");
}
}
  注意:这种⽅式是依赖注⼊Evnironment来完成,在创建的成员变量private Environment env上加上@Autowired注解即可完成依赖注⼊,然后使⽤Property("键名")即可读取出对应的值。
⼆、读取⾃定义配置⽂件
  为了不破坏核⼼⽂件的原⽣态,但⼜需要有⾃定义的配置信息存在,⼀般情况下会选择⾃定义配置⽂件来放这些⾃定义信息,这⾥
在resources/config⽬录下创建配置⽂件my-web.properties
  resources/config/my-web.properties内容如下:
web.name=zslin
web.version=V 1.0
web.author=393156105@qq
1、创建管理配置的实体类:
袁立五花肉事件是什么
  需要⽤到2个注解:@ConfigurationProperties
  @Component,把该类变成spring的⼀个组件
@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;
}
}
  注意:
  (1)在@ConfigurationProperties注释中有两个属性:
王凯有妻子吗
  locations:指定配置⽂件的所在位置
  prefix:指定配置⽂件中键名称的前缀(我这⾥配置⽂件中所有键名都是以web.开头)
  (2)使⽤@Component是让该类能够在其他地⽅被依赖使⽤,即使⽤@Autowired注释来创建实例。
2、创建测试Controller
@RestController
@RequestMapping(value = "config")
public class ConfigController {
@Autowired
private MyWebConfig myWebConfig;
@RequestMapping(value = "index", method = RequestMethod.GET)张子枫艺考全国第三
花少3public String index() {
读取配置文件失败
return"webName: "+Name()+", webVersion: "+
}
}
  注意:由于在MyWebConfig类上加了注释@Component,所以可以直接在这⾥使⽤@Autowired来创建其实例对象。