【spring boot】SpringBoot初学(2.2)– SpEL表达式读取properties属性到Java对象
前言
github: https://github.com/vergilyn/SpringBootDemo
代码位置:(注意测试方法在,test下的SpelValueApplicationTest.class)

一、什么是SpEL
SpEL:spring表达式语言,Spring Expression Language。从spring3开始引入。
可以通过xml或注解的施行映射properties中的属性到JavaBean,并通过Spring注入。
二、Spring boot中常见的应用
@Value("${base.name}")
private String baseName;
@Value("#{'string'}") // 或 @Value('#{"string"}')
public String spelString;
(个人理解) 以$开头的只是普通模式,而以#开头的才是SpEL。
针对这两种,它们默认值的写法也是不一样的。
${ property : default_value }
#{ obj.property ?: default_value }
三、以$取值
## value-base.propertiesbase.name=vergil
base.song=Safe&Sound
base.nest.song=base.song
package com.vergilyn.demo.spring.value.property; import java.util.Calendar;
import java.util.Date; import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component; @PropertySource("classpath:config/value/value-base.properties")
@Component("base")
public class BaseProperty {
@Value("${base.name}")
private String baseName;
@Value("${base.song}")
private String baseSong;
/* 嵌套(内往外)
* 解析:先取内部${base.nest.song}=base.song -> ${base.song} = Safe&Sound
*/
@Value(value = "${${base.nest.song}}")
private String nestSong; @Override
public String toString() {
return this.getClass().getSimpleName() +":{baseName: "+this.baseName+", baseSong: "+this.baseSong+"}";
} public String getBaseName() {
return baseName;
}
public void setBaseName(String baseName) {
this.baseName = baseName;
}
public String getBaseSong() {
return baseSong;
}
public void setBaseSong(String baseSong) {
this.baseSong = baseSong;
} public String getNestSong() {
return nestSong;
} public void setNestSong(String nestSong) {
this.nestSong = nestSong;
} public Date nowDate(){
return Calendar.getInstance().getTime();
}
}
结果:
BaseProperty: {"baseName":"vergil","baseSong":"Safe&Sound","nestSong":"Safe&Sound"}
四、以#取值 一般形式
## value-spel.propertiesspel.name=dante
spel.mix=baseSong
package com.vergilyn.demo.spring.value.property; import java.util.Date; import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component; @PropertySource("classpath:config/value/value-spel.properties")
@Component
public class SpelProperty { @Value("${spel.name}") //注意这里是 $
private String spelName;
/* base:指BaseProperty.class(默认为baseProperty),因为定义了@Component("base")
* baseSong:并不是*.properties中的key,而是此key对应的class变量
*/
@Value("#{base.baseSong}")
private String spelSong;
/* // @Value("${ '#{base.baseSong}' }") //这个不支持。因为#开头的才是spel。
* 解析:由内往外,${spel.mix} = baseSong。然后在spel表达式中,('')表示定义字符串。
* 所以 #{'baseSong'} = baseSong
*/
@Value("#{ '${spel.mix}' }")
private String mixSong;
@Value("#{base. ${spel.mix} }") //组合,特别.后面跟的是对象属性。所以要是class中的属性,而不是properties中的key
private String mixSong2; public String getMixSong2() {
return mixSong2;
}
public void setMixSong2(String mixSong2) {
this.mixSong2 = mixSong2;
}
public String getSpelName() {
return spelName;
}
public void setSpelName(String spelName) {
this.spelName = spelName;
}
public String getSpelSong() {
return spelSong;
}
public void setSpelSong(String spelSong) {
this.spelSong = spelSong;
} public String getMixSong() {
return mixSong;
}
public void setMixSong(String mixSong) {
this.mixSong = mixSong;
}
}
结果:
SpelProperty: {"mixSong":"baseSong","mixSong2":"Safe&Sound","spelName":"dante","spelSong":"Safe&Sound"}
四、以#取值 各种复杂形式
package com.vergilyn.demo.spring.value.property; import java.util.Date; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; @Component
public class SpelBasisProperty { @Value("#{124}")
public int spelInt;
@Value("#{124.24}")
public float spelFloat;
@Value("#{1e4}")
public double spelSpec;
@Value("#{true}")
public boolean spelBoolean = false;
@Value("#{'string'}") // 或 @Value('#{"string"}')
public String spelString;
/* 调用方法。
* 在SpEL中避免抛出空指针异常(NullPointException)的方法是使用null-safe存取器:
* ?. 运算符代替点(.) #{object?.method()},如果object=null,则不会调用method()
*/
@Value("#{base.getNestSong()}")
public String spelNestSong;
@Value("#{base.nowDate()}") //返回值可以是任何类型
public Date spelNowDate;
@Value("#{null?.toString()}") //当?.左边为null时,不再执行右边的方法。(避免NPE)
public String spelNull; /**
* 在SpEL中,使用T()运算符会调用类作用域的方法和常量。
*/
@Value("#{T(java.lang.Math).PI}")
public double T_PI;
@Value("#{T(java.lang.Math).random()}")
public double T_andom; /**
* SpEL运算>>>>
* 四则运算:+ - * /
* 比较:eq(==),lt(<),le(<=),gt(>),ge(>=)。
* 逻辑表达式:and,or,not或!。
* 三元表达式:
* i. #{base.name == 'vergilyn' ? true : false}
* ii. #{base.name == 'vergilyn' ? base.name : 'dante'}
* spel可以简化为:#{base.name ?: 'dante'} 当base.name !=null则取base.name,否则取'dante'。
* (?:)通常被称为elvis运算符。
* 正则:#{base.song matches '[a-zA-Z0-9._%+_]+@[a-zA-Z0-9.-]+\\.com'} 。 (不光有matches,还有很多别的,可详细baidu/google)
*/
@Value("#{100 / 20}") //四则运算: + - * /
public int spelArithmetic;
}
结果:
SpelBasisProperty: {"T_PI":3.141592653589793,"T_andom":0.49286684542729553,"spelArithmetic":5,"spelBoolean":true,"spelFloat":124.24,"spelInt":124,"spelNestSong":"Safe&Sound","spelNowDate":1489169611736,"spelSpec":10000.0,"spelString":"string"}
【spring boot】SpringBoot初学(2.2)– SpEL表达式读取properties属性到Java对象的更多相关文章
- Spring Boot]SpringBoot四大神器之Actuator
论文转载自博客: https://blog.csdn.net/Dreamhai/article/details/81077903 https://bigjar.github.io/2018/08/19 ...
- spring Boot启动报错Initialization of bean failed; nested exception is java.lang.NoSuchMethodError: org.springframework.core.annotation.AnnotatedElementUtils.getAnnotationAttributes
spring boot 启动报错如下 org.springframework.context.ApplicationContextException: Unable to start web serv ...
- (五)Spring Boot之@RestController注解和ConfigurationProperties配置多个属性
一.@RestController和@Controller的区别 @RestController注解相当于@ResponseBody + @Controller合在一起的作用. 如果只是使用@Rest ...
- [Spring Boot] Set Context path for application in application.properties
If you were using Microservice with Spring Boot to build different REST API endpoints, context path ...
- 曹工说Spring Boot源码(5)-- 怎么从properties文件读取bean
写在前面的话 相关背景及资源: 曹工说Spring Boot源码(1)-- Bean Definition到底是什么,附spring思维导图分享 曹工说Spring Boot源码(2)-- Bean ...
- 【spring boot】映射properties文件属性--到Java对象
描述 将*.properties中的内容映射到java对象中: 主要步骤 添加 @Component 注解: 使用 @PropertySource 注解指定配置文件位置: 使用 @Configurat ...
- spring利用注解方式实现Java读取properties属性值
1. 建立properties文件:我在resource下面建立一个config文件夹,config文件夹里面有mytest.properties文件,文件内容如下: sam.username=sam ...
- Spring Boot系列教程四:配置文件详解properties
一.配置随机数,使用随机数 在application.properties文件添加配置信息 #32位随机数 woniu.secret=${random.value} #随机整数 woniu.numbe ...
- 解决 spring boot 线程中使用@Autowired注入Bean的方法,报java.lang.NullPointerException异常
问题描述 在开发中,因某些业务逻辑执行时间太长,我们常使用线程来实现.常规服务实现类中,使用 @Autowired 来注入Bean,来调用其中的方法.但如果在线程类中使用@Autowired注入的Be ...
随机推荐
- c++ 初始化列表和构造函数初始化区别
先上代码 #include <iostream> class MyContruct { public: MyContruct() { std::cout << "My ...
- LVS 部署
一.LVS的组成 LVS 由2部分程序组成,包括 ipvs 和 ipvsadm. 1. ipvs(ip virtual server):一段代码工作在内核空间,叫ipvs,是真正生效实现调度的代码.2 ...
- CentOS 7的yum更换为国内的阿里云yum源
Yellow dog Updater(Yum)是CentOS所有版本的默认包管理器,yum主要功能是更方便的添加/删除/更新RPM包,自动解决包的依赖性问题,便于管理大量系统的更新问题,其理念是使用一 ...
- k8s系列---部署集群
docer启动出错 [root@centos-minion yum.repos.d]# systemctl start docker Job for docker.service failed bec ...
- shell脚本 监控ps 不存在则重启
监控 tomcat ,如果自动停止了,则重新启动 #!/bin/bash Start=/usr/local/apache-tomcat-8.0.24/bin/startup.sh Url=" ...
- Arm开发板+Qt学习之路-multiple definition of
问题描述:在一个头文件a.h中定义一些变量x,在其他.c文件中(b.c,c.c)要用到.用一般的全局变量的方法,编译时总是提示error:multiple definition of x 问题分析:o ...
- 删掉以前的旧Flow,创作现在的新节奏
2017年开始实习,现已2020年.三年又三年.今天我删掉无知的从前,进入新世界. 无论活的多累 做人不进则退 只能自我激励 将这当做基地
- cesium1.63.1api版本贴地贴模型量算工具效果(附源码下载)
前言 cesium 官网的api文档介绍地址cesium官网api,里面详细的介绍 cesium 各个类的介绍,还有就是在线例子:cesium 官网在线例子,这个也是学习 cesium 的好素材.不少 ...
- linux中压缩解压缩命令
目录 gzip gunzip tar(打包压缩) tar(解包解压) zip unzip bzip2 bunzip2 gzip 解释 命令名称:gzip 命令英文原意:GUN zip 命令所在路径:/ ...
- Azure Media Services -可提供视频点播(VOD)
Azure Media Services 提供直播/VOD点播相关的功能. •提供编码和打包以适用于各种设备播放视频(IOS/Android/web等). •向大量在线观众流式传输实时直播,例如活动 ...