阿里巴巴网站域名注册,怎么自己设计logo,物流运输网,广东省做网站的公司方式一#xff1a;Value
基本类型属性注入#xff0c;直接在字段上添加Value(${xxx.xxx})即可#xff0e;注意这里用的是$#xff0c;而不是##xff0c;Value注入的属性#xff0c;一般其他属性没有关联关系。
配置文件
user:name: Manaphyage: 19sex: m…方式一Value
基本类型属性注入直接在字段上添加Value(${xxx.xxx})即可注意这里用的是$而不是#Value注入的属性一般其他属性没有关联关系。
配置文件
user:name: Manaphyage: 19sex: maleRestController
public class ConfigPropertiesController {Value(${user.name})private String name;Value(${user.age})private Integer age;Value(${user.sex})private String sex;GetMapping(/user)public String getUser() {return {name: name ,age: age ,sex: sex };}
}方式二ConfigurationProperties
配置文件
person:lastName: helloage: 18boss: falsebirth: 2017/12/12maps: {k1: v1,k2: v2}lists:- lisi- wangwudog:name: 小狗age: 12JavaBean
/*** 将配置文件中配置的每一个属性的值映射到这个组件中* ConfigurationProperties告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定;* prefix person配置文件中哪个下面的所有属性进行一一映射* 只有这个组件是容器中的组件才能容器提供的ConfigurationProperties功能*/
Component
ConfigurationProperties(prefix person)
Data
public class Person {private String lastName;private Integer age;private Boolean boss;private Date birth;private MapString, Object maps;private ListObject lists;private Dog dog;}Data
class Dog {private String name;private Integer age;
}Controller层
RestController
public class PersonController {Autowiredprivate Person person;GetMapping(/person)public Person getPerson() {return person;}
}运行结果如下
我们可以导入配置文件处理器以后编写配置就有提示了
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-configuration-processor/artifactIdoptionaltrue/optional
/dependency注意使用ConfigurationProperties注入属性时如果只给属性提供get方法会报错
例
/*** yml配置*/
sms:region-id: cn-shanghaiaccess-key-id: 123access-key-secret: 123sign-name: 叮咚买菜/*** 实体类*/
Getter
Component
ConfigurationProperties(prefix sms)
public class SmsProperties {private String regionId;private String accessKeyId;private String accessKeySecret;
}/*
报错
Description:Failed to bind properties under sms to com.example.producer.producerdemo.util.SmsProperties:Property: sms.access-key-idValue: 123Origin: class path resource [application.yml] - 51:18Reason: java.lang.IllegalStateException: No setter found for property: access-key-idAction:Update your applications configuration
*/Value和ConfigurationProperties比较
ConfigurationPropertiesValue功能批量注入配置文件中的属性一个个指定松散绑定松散语法支持不支持SpEL不支持支持JSR303数据校验支持不支持复杂类型封装支持不支持
配置文件yml还是properties他们都能获取到值
如果说我们只是在某个业务逻辑中需要获取一下配置文件中的某项值使用Value
如果说我们专门编写了一个javaBean来和配置文件进行映射我们就直接使用ConfigurationProperties。