tags: [springboot]
categories: [基本使用]
写在前面
之前做SpringBoot项目时,所有的属性注入都是通过YML里面配置文件来配合@Value注解来注入的,这次开发时,试着注入数组发现@Value注解不支持,借着这个机会,重新研究了SrpingBoot属性注入的几种方法,以及适合的各种各样的场景
属性注入
@Value注解注入
基本使用
这是最常见的用法,我们在配置文件中自定义标签aaa.bbb,值为简单数据类型,然后在需要使用该属性的地方加上@Value注解,注解Value属性值为${"aaa.bbb"}直接使用@Value注解下的定义的字段,如
############### 属性注入 ##############################email:sender: 'bwensun@foxmail.com'# 邮件thymeleaf模板路径template:captcha: mail/captcha
@Component@Slf4jpublic class EmailService {@Value("${email.sender}")String emailSender;@Value("${email.template.captcha}")String captchaTemplate;}
value注解可以通过冒号设置默认值
@Value("${server.port:8080}") //没有设置则默认设为8080private String port;
也可以注入数组和List,注意默认以都好分割,在YML中的数组和List
tools=car,train,airplane
/*** 注入数组(自动根据","分割)*/@Value("${tools}")private String[] toolArray;/*** 注入列表形式(自动根据","分割)*/@Value("${tools}")private List<String> toolList;
注入非配置文件中的属性(事实上都是spring已知的信息),可以接口SPEL表达式使用
/*** 注入普通字符串,相当于直接给属性默认值*/@Value("程序新视界")private String wechatSubscription;/*** 注入操作系统属性*/@Value("#{systemProperties['os.name']}")private String systemPropertiesName;/*** 注入表达式结果*/@Value("#{ T(java.lang.Math).random() * 100.0 }")private double randomNumber;/*** 注入其他Bean属性:注入config对象的属性tool*/@Value("#{config.tool}")private String tool;/*** 注入列表形式(自动根据"|"分割)*/@Value("#{'${words}'.split('\\|')}")private List<String> numList;/*** 注入文件资源*/@Value("classpath:config.xml")private Resource resourceFile;/*** 注入URL资源*/@Value("http://www.choupangxia.com")private URL homePage;
@ConfigurationProperties注解
相比于@``Value注解,@ConfigurationProperties需要做的使用更多,我们需要新建一个结构和注入属性接口一致的类,配置@ConfigurationProperties和@Configuration注解来,就把他当作一个一般的bean,通过注入的方式来获取该对象的值
# zoombarzoombar:whitelist:- 'login'jwtSecretKey: 'zoombar.fun'token:expiredTime: 365
@Configuration@ConfigurationProperties(prefix = "zoombar")@Getter@Slf4j@Setterpublic class ZoombarProperties {/*** 白名单*/public List<String> whitelist;/*** jwt密钥*/private String jwtSecretKey;@PostConstructpublic void init(){log.info("ZoombarProperties 属性注入成功");}}
