javascript
Springboot-读取核心配置文件及自定义配置文件
读取核心配置文件
核心配置文件是指在resources根目录下的application.properties或application.yml配置文件,读取这两个配置文件的方法有两种,都比较简单。
核心配置文件application.properties内容如下:
server.port=9090 test.msg=Hello World Springboot!-
使用@Value方式(常用)
注意:在@Value的${}中包含的是核心配置文件中的键名。在Controller类上加@RestController表示将此类中的所有视图都以JSON方式显示,类似于在视图方法上加@ResponseBody。
访问:http://localhost:9090/index 时将得到The Way 1 : Hello World Springboot!
-
使用Environment方式
访问:http://localhost:9090/index2 时将得到The Way 2 : Hello World Springboot!
读取自定义配置文件
-
通过@ConfigurationProperties注解,通过getter、setter方法注入及获取配置
为了不破坏核心文件的原生态,但又需要有自定义的配置信息存在,一般情况下会选择自定义配置文件来放这些自定义信息,这里在resources/config目录下创建配置文件my-web.properties
resources/config/my-web.properties内容如下:
web.name=isea533web.jdbc.username=root
web.jdbc.password=root
创建管理配置的实体类:
@ConfigurationProperties(locations = "classpath:config/my-web.properties", prefix = "web") @Component public class MyWebConfig{private String name;private Jdbc jdbc;class Jdbc {private String username;private String password;//getter... }public Integer gePort(){return this.port;}public Jdbc getJdbc() {return this.jdbc;} } 注意:在@ConfigurationProperties注释中有两个属性:
- locations:指定配置文件的所在位置
- prefix:指定配置文件中键名称的前缀(我这里配置文件中所有键名都是以web.开头)
使用@Component是让该类能够在其他地方被依赖使用,即使用@Autowired注释来创建实例。
-
通过@PropertySource注解,然后使用@Value逐个注入配置
转载于:https://www.cnblogs.com/junzi2099/p/7509045.html
总结
以上是生活随笔为你收集整理的Springboot-读取核心配置文件及自定义配置文件的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: java标识符的规则等
- 下一篇: JS中的!= 、== 、!==、===的