SpringBoot 学习记录(八): properties 属性自定义

    xiaoxiao2021-04-18  50

    这篇我们来学习如何在java bean 中使用我们自定义的属性

    一,引入依赖包

    <!-- 支持自定义配置参数 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>二,在application.properties中自定义属性参数,这里分几种情况

    1) 单个属性参数

    先在application.properties中定义几个属性:

    com.demo.title=big.title com.demo.description=test com.demo.num=${random.int} com.demo.value=${random.value} com.demo.msg=\u6D4B\u8BD5\u6807\u9898\uFF1A${com.demo.title}这里说明一下:

    num:可以使用random生成随机数,引用方法有

    ${random.int}

    ${random.long}

    ${random.int(10)} == 10以内的随机数

    ${random.int[10,20]} == 10-20的随机数

    value:可以使用random生成随机字符串(32位)

    msg:可以引用文件内部定义的属性值,引用方法${key}

    新建java类DemoProperties,注入自定义的属性值,这里主要使用注解@Value

    package com.example.properties; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component//交由spring管理 public class DemoProperties { /** * 给定一个默认值,当读取不到key值com.demo.title时启用默认值 */ @Value("${com.demo.title:default.title}") private String title; /** * 没有给定默认值,当读取不到key值时会抛异常 */ @Value("${com.demo.description}") private String description; /** * 随机数 */ @Value("${com.demo.num}") private String num; /** * 随机字符串 */ @Value("${com.demo.value}") private String value; /** * 内部引用属性 */ @Value("${com.demo.msg}") private String msg; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getNum() { return num; } public void setNum(String num) { this.num = num; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } 新建测试类ConfigController package com.example.controller; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.example.base.ReturnResult; import com.example.constant.ReturnConstant; import com.example.properties.ConfigProperties; import com.example.properties.DemoProperties; /** * 测试读取自定义属性 * @author Administrator * */ @RestController @RequestMapping("/properties") public class ConfigController { @Resource private DemoProperties demoProperties; @RequestMapping("/demo") public ReturnResult getDemoProp(){ Map<String,Object> map = new HashMap<String,Object>(); map.put("demo", demoProperties); ReturnResult r = new ReturnResult(); r.setStatus(ReturnConstant.RETURN_OK); r.setMsg("自定义单个属性"); r.setResult(map); return r; } } 访问测试: http://localhost:8088/spring-boot/properties/demo

    返回结果如下:

    { "status": "true", "msg": "自定义单个属性", "result": { "demo": { "title": "big.title", "description": "test", "num": "2050553421 ", "value": "09f706565ea9d4a961278578039e073f", "msg": "测试标题:big.title" } } }2) 多个属性参数

    先在application.properties中定义几个属性:

    com.conf.group.name=group com.conf.group.number=10 com.conf.group.system=\u4EBA\u5458\u7BA1\u7406 com.conf.group.local-path=127.0.0.1:8080 com.conf.group.user[0]=Lily com.conf.group.user[1]=Sam com.conf.group.user[2]=Jessie这里说明一下:

    属性local-path不符合java命名规范,注入时参数名可以用localPath来匹配

    属性user是定义的一个数组,注入时用list来接收参数

    新建java类ConfigProperties,注入自定义的属性值,这里主要使用注解@ConfigurationProperties

    package com.example.properties; import java.util.List; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import com.example.entity.TestUser; @Component//交由spring管理 //prefix设置key的前缀; @ConfigurationProperties(prefix="com.conf.group") public class ConfigProperties { /** * 属性后缀要对应配置文件中设置的key * key值有-连接符的可以自动匹配为java规范命名 * 定义的数组用集合封装 */ private String name; private int number; private String system; private String localPath; private List<String> user; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public String getSystem() { return system; } public void setSystem(String system) { this.system = system; } public String getLocalPath() { return localPath; } public void setLocalPath(String localPath) { this.localPath = localPath; } public List<String> getUser() { return user; } public void setUser(List<String> user) { this.user = user; } } 在ConfigController中添加测试方法: package com.example.controller; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.example.base.ReturnResult; import com.example.constant.ReturnConstant; import com.example.properties.ConfigProperties; import com.example.properties.DemoProperties; /** * 测试读取自定义属性 * @author Administrator * */ @RestController @RequestMapping("/properties") public class ConfigController { @Resource private DemoProperties demoProperties; @Resource private ConfigProperties configProperties; @RequestMapping("/demo") public ReturnResult getDemoProp(){ Map<String,Object> map = new HashMap<String,Object>(); map.put("demo", demoProperties); ReturnResult r = new ReturnResult(); r.setStatus(ReturnConstant.RETURN_OK); r.setMsg("自定义单个属性"); r.setResult(map); return r; } @RequestMapping("/conf") public ReturnResult getConfProp(){ Map<String,Object> map = new HashMap<String,Object>(); map.put("conf", configProperties); ReturnResult r = new ReturnResult(); r.setStatus(ReturnConstant.RETURN_OK); r.setMsg("自定义多个属性"); r.setResult(map); return r; } } 启动服务,访问测试: http://localhost:8088/spring-boot/properties/conf

    返回结果如下:

    { "status": "true", "msg": "自定义多个属性", "result": { "conf": { "name": "group", "number": 10, "system": "人员管理", "localPath": "127.0.0.1:8080", "user": [ "Lily", "Sam", "Jessie" ] } } } 三,除了在默认的application.properties中定义属性,我们还可以自定义一个properties文件

    config.properties

    com.conf.group.name=group com.conf.group.number=5 com.conf.group.system=\u4EBA\u5458\u7BA1\u7406 com.conf.group.local-path=127.0.0.1:8088 com.conf.group.user[0]=Lucy com.conf.group.user[1]=Susan com.conf.group.user[2]=Joly这里方便测试,属性key值没有变,只是改变了value值

    那么给java类ConfigProperties注入属性值时如何指定配置文件呢?

    很简单,只需要在注解@ConfigurationProperties中添加一个属性:locations="classpath:config.properties"

    @Component//交由spring管理 //prefix设置key的前缀; @ConfigurationProperties(prefix="com.conf.group",locations="classpath:config.properties") public class ConfigProperties { }启动测试,看是否读取的是config.properties中的属性值

    http://localhost:8088/spring-boot/properties/conf

    查看返回结果:

    {   "status": "true",   "msg": "自定义properties文件,定义多个属性",   "result": {     "conf": {       "name": "group",       "number": 5,       "system": "人员管理",       "localPath": "127.0.0.1:8088",       "user": [         "Lucy",         "Susan",         "Joly"       ]   } }

    可以看到,读取到的属性值确实已经改变了。

    四,在配置文件中我们还可以定义一个对象的属性值,首先在 config.properties中添加如下属性: com.conf.group.testUser.name=user_name com.conf.group.testUser.age=22 com.conf.group.testUser.gender=M这里的属性值testUser将由一个自定义的对象来接收,

    我们定义一个普通java类TestUser,在其中定义匹配的属性名

    package com.example.entity; /** * 自定义属性可以用实体类来接收 * @author Administrator * */ public class TestUser { private String name; private int age; private String gender; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } } 在ConfigProperties中添加属性: private TestUser testUser; public TestUser getTestUser() { return testUser; } public void setTestUser(TestUser testUser) { this.testUser = testUser; }再来测试: http://localhost:8088/spring-boot/properties/conf

    返回结果如下:

    { "status": "true", "msg": "自定义properties文件,定义多个属性", "result": { "conf": { "name": "group", "number": 5, "system": "人员管理", "localPath": "127.0.0.1:8088", "user": [ "Lucy", "Susan", "Joly" ], "testUser": { "name": "user_name", "age": 22, "gender": "M" } } } }五,以上都是通过java类直接注入属性值,下面我们来看如何在注入bean的时候注入自定义属性

    1) 删除ConfigProperties的类注解,使其成为一个普通java类

    package com.example.properties; import java.util.List; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import com.example.entity.TestUser; //@Component//交由spring管理 //prefix设置key的前缀; //@ConfigurationProperties(prefix="com.conf.group",locations="classpath:config.properties") public class ConfigProperties { /** * 属性后缀要对应配置文件中设置的key * key值有-连接符的可以自动匹配为java规范命名 * 定义的数组用集合封装 */ private String name; private int number; private String system; private String localPath; private List<String> user; private TestUser testUser; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public String getSystem() { return system; } public void setSystem(String system) { this.system = system; } public String getLocalPath() { return localPath; } public void setLocalPath(String localPath) { this.localPath = localPath; } public List<String> getUser() { return user; } public void setUser(List<String> user) { this.user = user; } public TestUser getTestUser() { return testUser; } public void setTestUser(TestUser testUser) { this.testUser = testUser; } } 2) 在DemoApplication启动类中注入bean,完整代码如下: package com.example; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import com.example.properties.ConfigProperties; @SpringBootApplication @MapperScan("com.*.mapper")//扫描该包下接口 public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Bean @ConfigurationProperties(prefix="com.conf.group",locations="classpath:config.properties") public ConfigProperties configProperties(){ return new ConfigProperties(); } } 启动测试: http://localhost:8088/spring-boot/properties/conf

    查看返回结果:

    { "status": "true", "msg": "自定义properties文件,定义多个属性", "result": { "conf": { "name": "group", "number": 5, "system": "人员管理", "localPath": "127.0.0.1:8088", "user": [ "Lucy", "Susan", "Joly" ], "testUser": { "name": "user_name", "age": 22, "gender": "M" } } } }可以看到,这里的结果跟上面是一样的,说明注入属性成功。

    ===========================================================================

    关于自定义属性的学习就到此结束,参考博文:http://412887952-qq-com.iteye.com/blog/2311017

    下篇我们将学习,SpringBoot 学习记录(九): Email

    转载请注明原文地址: https://ju.6miu.com/read-674750.html

    最新回复(0)