springboot2常用技能(@Value、@ConfigurationProperties、自定义配置文件、Junit、多环境配置)

一、使用@Value进行属性配置

1.创建User类,写入属性,重写toString方法。
springboot2常用技能(@Value、@ConfigurationProperties、自定义配置文件、Junit、多环境配置)
2.在自带的配置文件application.properties中插入值
springboot2常用技能(@Value、@ConfigurationProperties、自定义配置文件、Junit、多环境配置)
3.在User类中使用@Value进行属性注入
springboot2常用技能(@Value、@ConfigurationProperties、自定义配置文件、Junit、多环境配置)
4.到controller中注入User类后,直接return回toString方法。
springboot2常用技能(@Value、@ConfigurationProperties、自定义配置文件、Junit、多环境配置)
5.启动springboot,浏览中可查看运行结果。成功。
springboot2常用技能(@Value、@ConfigurationProperties、自定义配置文件、Junit、多环境配置)
6.总结:
springboot2常用技能(@Value、@ConfigurationProperties、自定义配置文件、Junit、多环境配置)

二、使用@ConfigurationProperties进行属性配置

1.类上加注解,添加前缀,前缀和配置文件application.properties中的前缀一致。
springboot2常用技能(@Value、@ConfigurationProperties、自定义配置文件、Junit、多环境配置)
2.运行,查看浏览器,成功。(结果和刚才一致,不重复放图了哦)

三、使用自定义配置文件,不用springboot自带的默认配置文件

1.自定义配置文件并将默认配置文件application.properties中的内容剪切过来。
springboot2常用技能(@Value、@ConfigurationProperties、自定义配置文件、Junit、多环境配置)
2.在springboot自带的启动类中配置@PropertySource并写入自定义配置文件的路径。
springboot2常用技能(@Value、@ConfigurationProperties、自定义配置文件、Junit、多环境配置)
3.运行,查看浏览器,成功。(结果和刚才一致,不重复放图了哦)

四、springboot中Junit单元测试的使用

1.定义工具类,实现接口ApplicationContextAware,使得这个类可以获得ApplicationContext中的所有bean。
(ApplicationContext隶属于org.springframework.context,是SpringFramework中Bean的管理者)

ApplicationContext详解参考博文:
https://www.jianshu.com/p/498e64bf0a44
springboot2常用技能(@Value、@ConfigurationProperties、自定义配置文件、Junit、多环境配置)
2.在springboot的测试类中添加Junit测试
springboot2常用技能(@Value、@ConfigurationProperties、自定义配置文件、Junit、多环境配置)
3.启动测试类,控制台可获得输出结果
springboot2常用技能(@Value、@ConfigurationProperties、自定义配置文件、Junit、多环境配置)

五、多环境配置

首先了解环境:
springboot2常用技能(@Value、@ConfigurationProperties、自定义配置文件、Junit、多环境配置)
针对多环境带来的问题,springboot的解决方式:为不同的环境编写不同的配置文件,需要时进行设置。
springboot2常用技能(@Value、@ConfigurationProperties、自定义配置文件、Junit、多环境配置)
通过代码实现的具体解决方案:

方案一:使用properties文件格式的配置文件进行配置

1.分别编写2个配置文件,定义环境端口号。
springboot2常用技能(@Value、@ConfigurationProperties、自定义配置文件、Junit、多环境配置)
springboot2常用技能(@Value、@ConfigurationProperties、自定义配置文件、Junit、多环境配置)
2.在默认配置文件application.properties定义生效环境。
springboot2常用技能(@Value、@ConfigurationProperties、自定义配置文件、Junit、多环境配置)
3.运行以后显示的tomcat端口为8081。
springboot2常用技能(@Value、@ConfigurationProperties、自定义配置文件、Junit、多环境配置)

方案二:使用yml格式的配置文件进行配置

1.创建yml文件,并定义多环境和端口。
(yml格式文件和properties文件不能同时使用,使用一方建议删除另一方或对另一方进行完全注释)
springboot2常用技能(@Value、@ConfigurationProperties、自定义配置文件、Junit、多环境配置)
2.运行,查看端口为8082.
springboot2常用技能(@Value、@ConfigurationProperties、自定义配置文件、Junit、多环境配置)
yml文件优点:只需要在一个文件中进行配置,不需要分多个文件去完成。