【SpringBoot】@ConfigurationProperties 及 @Value 注入示例

其他示例: 配置文件中Map和List类型如何配置

@ConfigurationProperties 注入示例

dog:
  age: 12
  hobbies: #[吃喝睡, 打豆豆]
    - 吃喝睡
    - 打豆豆
  scores:  #{eq: 90, iq: 85}
    eq: 90
    iq: 85
  groups:  #{one: {num: 2}, two: {len: 4, ok-go: 6}}
    one: {num: 2}
    two: {len: 4, ok-go: 6}
  name:    #{first-name: lao, last-name: liu}
    first-name: lao
    last-name:  liu
  names:   #[{first-name: su, last-name: si},{first-name: se, last-name: xi}]
    - {first-name: su, last-name: si}
    - {first-name: se, last-name: xi}
  friends: #{lila: {first-name: li, last-name: la},xihu: {first-name: xi, last-name: hu}}
    lila: {first-name: li, last-name: la}
    xihu: {first-name: xi, last-name: hu}
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.Map;

/**
 * @author LD
 * @description @ConfigurationProperties注入狗属性
 * @date 2023/3/29 15:58
 */
@Data
@Configuration
@ConfigurationProperties(prefix = "dog")
public class DogConfigProperties {
    private Integer age;
    private List<String> hobbies;
    private Map<String, Integer> scores;
    private Map<String, Map<String, Integer>> groups;
    private Name name;
    private List<Name> names;
    private Map<String, Name> friends;

    @Data
    public static class Name {
        private String firstName;
        private String lastName;
    }
}

@Value 注入示例

import cn.hutool.core.lang.TypeReference;
import cn.hutool.json.JSONUtil;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @author LD
 * @description @Value注入员工属性
 * <p>没有在配置文件中配置该 key 及其 value 时报错: `java.lang.IllegalArgumentException: Could not resolve placeholder 'man.xxx' in value "${man.xxx}"`</p>
 * <p>如果你想要支持不配置 key 程序也能正常运行的话,给其加上默认值`:`即可</p>
 * <p>除了`String`、8种基本类型和对应的包装类型 或 其`List`、`Array`外的数据类型,必须用`SpEL`才能解析,语法:`#{…}`,否则报错: java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'java.util.Map': no matching editors or conversion strategy found</p>
 * @date 2023/3/28 17:51
 */
@Data
@Component
public class ManValue {
    /**
     * <p>`@Value`注入简单属性</p>
     * <p>* 默认值`:`    ==> output: ""</p>
     * <p>* man.nick: tim ==> output: tim</p>
     */
    @Value("${man.nick:}")
    private String nick;
    /**
     * <p>`@Value`注入简单属性</p>
     * <p>* 默认值`:`  ==> output: null</p>
     * <p>* man.arm: 2 ==> output: 2</p>
     */
    @Value("${man.arm:}")
    private Integer arm;
    /**
     * <p>`@Value`注入数组</p>
     * <p>* 默认值`:` ==> output: []</p>
     * <p>* man.jobs: ui,go,ios ==> output: [ui,go,ios]</p>
     */
    @Value("${man.jobs:}")
    private String[] jobs;
    /**
     * <p>`@Value`注入数组</p>
     * <p>* 默认值`:` ==> output: []</p>
     * <p>* man.times: 11,22,33 ==> output: [11,22,33]</p>
     */
    @Value("${man.times:}")
    private Integer[] times;
    /**
     * <p>`@Value`注入列表</p>
     * <p>* 默认值`:` ==> output: []</p>
     * <p>* man.hobbies: 游戏,篮球,画画 ==> output: [游戏,篮球,画画]</p>
     * <p>> 低版本需使用`EL`表达式进行解析:</p>
     * <p>> * `#{'${man.hobbies:游戏,篮球}'.split(',')}` ==> output: [游戏,篮球]</p>
     * <p>> * `#{'${man.victors:}'.empty ? new String[0] : '${man.victors:}'.split(',')}` ==> output: null</p>
     */
    @Value("${man.hobbies:}")
//    @Value("#{'${man.hobbies:游戏,篮球}'.split(',')}")
    private List<String> hobbies;
    /**
     * <p>`@Value`注入列表</p>
     * <p>* 默认值`:` ==> output: []</p>
     * <p>* man.victors: 44,55,66 ==> output: [44,55,66]</p>
     */
    @Value("${man.victors:}")
//    @Value("#{'${man.victors:}'.empty ? new Integer[0] : '${man.victors:}'.split(',')}")
    private List<Integer> victors;
    /**
     * <p>`EL`表达式</p>
     * <p>`@Value`注入Map</p>
     * <p>* 默认值`#{${man.scores:{}}}` ==> output: null</p>
     * <p>* man.scores: {'eq': 99, 'iq': 88} ==> output: {eq=99, iq=88}</p>
     */
    @Value("#{${man.scores:{'eq': 90, 'iq': 85}}}")
    private Map<String, Integer> scores;
    
    /** 在配置文件配置好后, 以下3种方式项目启动报错:
     * `org.springframework.expression.spel.SpelEvaluationException: EL1004E: Method call: Method decode(java.util.Collections$UnmodifiableMap) cannot be found on type com.test.value.ManValue` 
     */
    /**
     * <p>`@Value`注入复杂类型(废弃)</p>
     * <p>* 默认值`#{${man.scores:{}}}` ==> output: null</p>
     * <p>* man.scores: {"firstName": "li", "lastName": "san"} ==> output: Name(firstName=li, lastName=san)</p>
     */
    @Deprecated
//    @Value("#{T(com.test.value.ManValue).decode(${man.name:'{\"firstName\": \"li\", \"lastName\": \"si\"}'})}")
    private Name name;
    /**
     * <p>`@Value`注入复杂类型(废弃)</p>
     * <p>* 默认值`#{${man.names:{}}}` ==> output: []</p>
     * <p>* man.scores: [{"firstName": "qi", "lastName": "liu"}] ==> output: [Name(firstName=qi, lastName=liu)]</p>
     */
    @Deprecated
//    @Value("#{T(com.test.value.ManValue).decodeList(${man.names:'[{\"firstName\": \"qi\", \"lastName\": \"liu\"}]'})}")
    private List<Name> names;
    /**
     * <p>`@Value`注入复杂类型(废弃)</p>
     * <p>* 默认值`#{${man.friends:{}}}` ==> output: null</p>
     * <p>* man.scores: {"kit": {"firstName": "er", "lastName": "niu"}} ==> output: {kit=Name(firstName=qi, lastName=liu)}</p>
     */
    @Deprecated
//    @Value("#{T(com.test.value.ManValue).decodeMap(${man.friends:'{\"kit\": {\"firstName\": \"er\", \"lastName\": \"niu\"}}'})}")
    private Map<String, Name> friends;

    @Data
    public static class Name {
        private String firstName;
        private String lastName;
    }
    
    public static ManValue.Name decode(String value) {
        try {
            return JSONUtil.toBean(value, new TypeReference<ManValue.Name>(){}, true);
            // return JSONObject.parseObject(value, new TypeReference<ManValue.Name>(){});
        } catch (Exception e) {
            return null;
        }
    }
    public static List<ManValue.Name> decodeList(String value) {
        try {
            return JSONUtil.toBean(value, new TypeReference<List<ManValue.Name>>(){}, true);
        } catch (Exception e) {
            return null;
        }
    }
    public static Map<String, ManValue.Name> decodeMap(String value) {
        try {
            return JSONUtil.toBean(value, new TypeReference<Map<String, ManValue.Name>>(){}, true);
        } catch (Exception e) {
            return null;
        }
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值