Springboot 之 自定义配置文件及读取配置文件
来源:互联网 发布:淘宝卖家版电脑版 编辑:程序博客网 时间:2024/05/17 23:20
读取核心配置文件
核心配置文件是指在resources根目录下的application.properties
或application.yml
配置文件,读取这两个配置文件的方法有两种,都比较简单。
核心配置文件application.properties
内容如下:
- 1
- 2
- 3
- 1
- 2
- 3
- 使用
@Value
方式(常用):
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
注意:在@Value
的${}中包含的是核心配置文件中的键名。在Controller类上加@RestController
表示将此类中的所有视图都以JSON方式显示,类似于在视图方法上加@ResponseBody
。
访问:http://localhost:9090/index 时将得到The Way 1 : Hello World Springboot!
- 使用
Environment
方式
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
注意:这种方式是依赖注入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
内容如下:
- 1
- 2
- 3
- 1
- 2
- 3
创建管理配置的实体类:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
注意:
在
@ConfigurationProperties
注释中有两个属性:locations
:指定配置文件的所在位置prefix
:指定配置文件中键名称的前缀(我这里配置文件中所有键名都是以web.
开头)
使用
@Component
是让该类能够在其他地方被依赖使用,即使用@Autowired
注释来创建实例。
创建测试Controller
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
注意:由于在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
本文章来自【知识林】
- Springboot 之 自定义配置文件及读取配置文件
- Springboot 之 自定义配置文件及读取配置文件
- Springboot 之 自定义配置文件及读取配置文件
- Springboot 之 自定义配置文件及读取配置文件
- Springboot 之 自定义配置文件及读取配置文件
- Springboot 之 自定义配置文件及读取配置文件
- 4.Springboot 之 自定义配置文件及读取配置文件
- springboot读取自定义配置文件
- SpringBoot 读取自定义配置文件
- SpringBoot之配置文件及自定义参数
- SpringBoot 读取配置文件及profiles切换配置文件
- springboot实战之读取配置文件
- SpringBoot读取配置文件乱码
- SpringBoot配置文件读取
- SpringBoot读取配置文件
- springboot读取配置文件
- springboot自定义配置文件
- springboot使用自定义配置文件
- 蓝桥杯练习题 BASIC-1 闰年判断
- css透明度的浏览器兼容以及div的隐藏和显示
- 【求一个数n的前几位】(pow函数)
- 文章标题
- Python数据类型 之 list
- Springboot 之 自定义配置文件及读取配置文件
- * 24种设计模式——解释器模式
- Reverse Bits 及format()总结
- 二分图匹配的一些概念
- 数据库事务ACID特性
- Git与Github教程
- Terminal
- React---Render
- 饭卡 HDU-2546 【01背包变形】