开发过程中经常会遇到参数配置化的情景,参数的类型也可以是多种多样的,记录一下各类型从配置文件中的加载方式,给当前创建一个savepoint。
配置一个properties文件
cc.common=abcdefcc.list=a,b,c,d,e,fcc.map={key1: '1', key2: '2', key3: '3'}
基础案例
1. 字符串
// 常规情况@Value("${cc.common}")private String common;// 自带默认值情况@Value("${cc.common1:aaa}")private String commonDefault;
2. 数组
@Value("${cc.list}")private String[] array;
3. List
@Value("#{'${cc.list}'.split(',')}")private List<String> list;
3. Map
// 常规情况@Value("#{${cc.map}}")private Map<String, Integer> map;// 单独某个key的value@Value("#{${cc.map}.key1}")private Integer value;// 根据value进行过滤@Value("#{${cc.map}.?[value>'1']}")private Map<String, Integer> mapFilter;// 默认值@Value("#{${cc.map:{key1: '11', key2: '12'}}}")private Map<String, Integer> map;

4. 自定义对象
@ConfigurationProperties(prefix = "cc")@Datapublic class PropertiesInject {private String common;private String[] list;}

5. 项目变量
// 获取所有系统变量@Value("#{@systemProperties}")private String systemProperty;// 获取指定系统变量@Value("#{@systemProperties['user.dir']}")private String systemPropertyList;// 获取所有系统变量,并以Map存储@Value("#{@systemProperties}")private Map<String, String> systemPropertyMap;

6. 系统环境变量
// 获取所有系统环境变量@Value("#{@systemEnvironment}")private Map<String, String> systemEnvironment;// 获取指定环境变量的值@Value("#{@systemEnvironment['PATH']}")private String systemEnvironmentPath;// 默认值@Value("#{@systemEnvironment['abc']?:'snowman'}")private String systemEnvironmentDefault;

注入方式
1. 属性注入
就是上方案例中的注入方式
2. 构造器注入
@Component@PropertySource("classpath:values.properties")public class PropertiesInject {private List<String> values = new ArrayList<>();@Autowiredpublic void setValues(@Value("#{'${cc.list}'.split(',')}") List<String> values) {this.values.addAll(values);}}
3. Setter注入
@Component@PropertySource("classpath:values.properties")public class PropertiesInject {private List<String> values = new ArrayList<>();@Autowiredpublic void setValues(@Value("#{'${cc.list}'.split(',')}") List<String> values) {this.values.addAll(values);}}
4. 类统一注入
@ConfigurationProperties(prefix = "cc")@Datapublic class PropertiesInject {private String common;private String[] list;}
文章转载自程序浪人,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




