首页 > 编程知识 正文

properties配置文件,springboot修改配置文件

时间:2023-05-04 04:08:39 阅读:145606 作者:1763

Spring Boot可以通过两种方法读取属性配置文件:

1,@value :一般用于各个属性值时,用这种方式直接注入

2、@ConfigurationProperties :前缀下包含多个属性值时,一般采用这种方式注入

1、通过@Value注释读取对应的数据内容,进行与配置文件对应的配置

server.port=8083 kq dxn.name=miaomaopackagecom .漂亮的发箍; importorg.spring framework.beans.factory.annotation.auto wired; importorg.spring framework.beans.factory.annotation.value; importorg.spring帧web.bind.annotation.request mapping; importorg.spring帧web.bind.annotation.rest controller; @ restcontrollerpublicclasshellocontroller { @ value (' $ { kq dxn.name } ' )专用字符串名称; @requestmapping(/Hello ) ) {return 'hello Spring Boot' name; }

因为可以直接从@value(${kqdxn.name ) } )获取对应的name值,所以不需要创建实体类

这里是注释,从application.properties获取了kqdxn.name的值

当我们在项目中,出现@value下的属性值未配置时:

@value (() $ (XXXX ) ) ) )时,未设置此xxxx的值,直接运行时可能会报告相应的错误。 此时,可以对未设定的属性值的内容赋予默认值,在“:对应的内容”中进行

格式: @value('${name2:xxxxx} ) )

如果未设置值name2,则会自动生成默认值" XXXX "

2、使用@ConfigurationProperties注释导入到实际项目中时,如果项目需要注入的变量值很多,则@value方法的工作量会变大。 在这种情况下,通常使用注释@configuration将属性与单个Bean相关联

server.port=8083 person.name=Xiaoming person.age=55 person, address=wudalu package com .漂亮的发箍. springBootTEST importorg.spring framework.beans.factory.annotation.value; importorg.spring framework.boot.context.properties.configuration properties; importorg.spring framework.stereotype.com ponent; @ component @ configuration properties (prefix=' person ' )公共类个人{ privatestring name; 私密int age; 私有字符串地址; public String getName () {return name; }公共语音集名称(字符串名称) {this.name=name; }public int getAge () {return age; }公共语音设置(intage ) {this.age=age; }公共字符串get地址(() {return address; } publicvoidsetaddress (字符串地址) {this.address=address; }公共人员(字符串名称、int age、字符串地址) {super ); this.name=name; this.age=age; this.address=address; }公共人员() ) {super ); //todo auto-generatedconstructorstub } @ overridepublicstringtostring () return'person(name='name ',age=' age }

@Component表示将类标识为Bean

@ configuration properties (prefix=' person ' )用于绑定属性,其中prefix表示所绑定的属性的前缀。

将这个前缀下面的对应属性值,直接注入至实体类的属性值中

如果未编写前缀,则需要此前缀,因为如果配置文件中有多个名称,则他可能无法识别它是人员下的名称值

在@ configuration properties (prefix=' person ' )中进行注释后,他不必像@value那样逐个放置,而是自动将配置文件中的对应属性值直接一一对应起来

时,使用@Autowired自动加载人员,然后取值。 例子如下所示。

package com .漂亮的发箍. springBootTEST.WEB; importorg.spring framework.beans.factory.annotation.auto wired; importorg.spring帧web.bind.annotation.request mapping; importorg.spring帧web.bind.annotation.rest controller; import com .漂亮的发箍. springBootTEST .想和人在一起的笑容; import com .漂亮的发箍. springBootTEST.Person; @ rest controller @ request mapping (hello2) ) publicclassonecontroller ) @autowiredprivatepersonperson; @RequestMapping (' ) public String hello ) ) system.out.println ) Person ); system.out.println(e43333 ); }

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。