当前位置: 首页 > 后端技术 > Java

第六节:SpingBoot的基本配置

时间:2023-04-02 01:12:16 Java

SpringBoot默认的配置文件是application.properties或application.yml。该文件会在应用启动时自动加载,无需手动导入。自定义属性定义属性值在application.properties#自定义属性rumenz.name=rumenzrumenz.url=https://rumenz.com通过@Value注解@RestController@RequestMapping("/rumenz")公共类获取值RumenzController{@Value("${rumenz.name}")privateStringrumenzName;@Value("${rumenz.url}")privateStringrumenzUrl;@RequestMapping("/index")publicStringindex(){returnrumenzName+"::::"+rumenzUrl;}}访问http://127.0.0.1:8080/rumenz/index路径,会返回rumenz::https://rumenz.com。当有时间配置绑定时,需要注入许多属性。一个一个装订很麻烦。官方建议是通过Bean加载。application.properties配置文件定义属性值com.rumenz.id=1com.rumenz.name=helloRumenzConfig配置文件@Component@ConfigurationProperties(prefix="com.rumenz")publicclassRumenzConfig{privateIntegerid;私有字符串名称;publicIntegergetId(){返回ID;}publicvoidsetId(Integerid){this.id=id;}publicStringgetName(){返回名称;}publicvoidsetName(Stringname){this.name=name;}}测试浏览器输入http://127.0.0.1:8080/rumenz/index1,返回1:::hello@RestController@RequestMapping("/rumenz")publicclassRumenzController{@AutowiredRumenzConfigrumenzConfig;@RequestMapping("/index1")publicStringindex1(){returnrumenzConfig.getId()+"::::"+rumenzConfig.getName();}}参数引用可以在application.properties中的参数之间直接引用,使用com.rumenz.id=1com.rumenz.name=hellocom.rumenz.des=${com.rumenz.name}${com.rumenz.id}newRumenzControllertest@RestController@RequestMapping("/rumenz")公共类朗姆酒enzController{@Value("${com.rumenz.des}")privateStringrumenzDes;@RequestMapping("/index2")publicStringindex2(){//配置文件参数参考//com.rumenz.des=${com.rumenz.name}${com.rumenz.id}returnrumenzDes;}}浏览器访问http://127.0.0.1:8080/rumenz/index2返回hello1自定义配置文件一般配置项在application中。在properties中,往往会有一些我们想要单独存放的配置信息。例如,我们创建了rumenz.properties的自定义配置文件。com.rumenz.tag=GettingStartedSmallSitecom.rumenz.txt=这是一个教程网站自定义配置文件系统不会自动加载,需要通过@PropertySource加载。需要加载多个可用设置数组。测试@RestController@RequestMapping("/rumenz")@PropertySource(value="classpath:rumenz.properties",encoding="utf-8")publicclassRumenz1Controller{@Value("${com.rumenz.tag}")私有字符串rumenzTag;@Value("${com.rumenz.txt}")privateStringrumenzTxt;@RequestMapping("/index3")publicStringindex3(){//这是自定义配置中配置的属性returnrumenzTag+rumenzTxt;}}浏览器访问http://127.0.0.1:8080/rumenz/index3,返回入口站这是一个加载多个自定义配置文件的教程网站@PropertySource(value={"classpath:rumenz.properties","classpath:rumenz2.properties",},encoding="utf-8")本摘要源地址:GitHub:https://github.com/mifunc/spr...Gitee:https://gitee.com/rumenz/spri...https://rumenz.com/rumenbiji/...介绍我的博客https://rumenz.com/我的工具箱https://tooltt.com/WeChat公众号:【入门小站】关注【入门】回复【1001】获取Linux常用命令速查手册关注【入门】回复【1003】获取LeetCode解答【Java语言实现】关注【入门】回复【1004】获取Java基础核心总结关注【入门站】回复【1009】获取阿里巴巴Java开发手册