核心配置文件是指在resources根目录下的application.properties或application.yml配置文件,读取这两个配置文件的方法有两种,都比较简单。
核心配置文件application.properties内容如下:
server.port=9090 test.msg=Hello World Springboot! 123 123 使用@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; } } 1234567891011 1234567891011注意:在@Value的${}中包含的是核心配置文件中的键名。在Controller类上加@RestController表示将此类中的所有视图都以JSON方式显示,类似于在视图方法上加@ResponseBody。
访问:http://localhost:9090/index 时将得到The Way 1 : Hello World Springboot!
使用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"); } } 123456789101112 123456789101112注意:这种方式是依赖注入Evnironment来完成,在创建的成员变量private Environment env上加上@Autowired注解即可完成依赖注入,然后使用env.getProperty("键名")即可读取出对应的值。
访问:http://localhost:9090/index2 时将得到The Way 2 : Hello World Springboot!
为了不破坏核心文件的原生态,但又需要有自定义的配置信息存在,一般情况下会选择自定义配置文件来放这些自定义信息,这里在resources/config目录下创建配置文件my-web.properties
resources/config/my-web.properties内容如下:
web.name=zslin web.version=V 1.0 web.author=393156105@qq.com 123 123注意:
在@ConfigurationProperties注释中有两个属性:
locations:指定配置文件的所在位置prefix:指定配置文件中键名称的前缀(我这里配置文件中所有键名都是以web.开头)使用@Component是让该类能够在其他地方被依赖使用,即使用@Autowired注释来创建实例。
注意:由于在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
本文章来自【知识林】