【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 ...
随机推荐
- 1. 学习Linux操作系统
1.熟练使用Linux命令行(鸟哥的Linux私房菜.Linux系统管理技术手册) 2.学会Linux程序设计(UNIX环境高级编程) 3.了解Linux内核机制(深入理解LINUX内核) 4.阅读L ...
- scala中符号的意思
1. => 定义函数, xxx => yyy 左边是函数变量,右边是函数返回值 2. <- 遍历中的<- 将变量赋给索引 for( i <- arrs ) 3. -> ...
- USBWebServer - 在U盘里搭一个Web服务器!
文章选自我的博客:https://blog.ljyngup.com/archives/321.html/ 本文将介绍一款可以在U盘内直接搭建Web服务器的软件 软件可以免安装直接在U盘内运行,适合外出 ...
- Wannafly挑战赛5 A珂朵莉与宇宙 前缀和+枚举平方数
Wannafly挑战赛5 A珂朵莉与宇宙 前缀和+枚举平方数 题目描述 给你一个长为n的序列a,有n*(n+1)/2个子区间,问这些子区间里面和为完全平方数的子区间个数 输入描述: 第一行一个数n 第 ...
- PyTorch可视化——tensorboard、visdom
一.pytorch与tensorboard结合使用 Tensorboard Tensorboard一般都是作为tf的可视化工具,与tf深度集成,它能够展现tf的网络计算图,绘制图像生成的定量指标图以及 ...
- Metasploit学习笔记(一) Samba服务 usermap_script安全漏洞相关信息
一.Samba介绍 Samba是linux和unix系统上实现smb协议的一个免费软件,由客户机和服务器构成.SMB是一种在局域网上实现共享文件和打印机的协议.存在一个服务器,客户机通过该协议可以服务 ...
- pytorch-- Attention Mechanism
1. paper: Learning Phrase Representations using RNN Encoder–Decoder for Statistical Machine Translat ...
- curl 和 tcpdump
curl: 1.通常使用curl 来监控网址状态, #curl -m 5 -s -o /dev/null -w %{http_code} www.baidu.com #200 -m 设置访问超时时间, ...
- [MacOS-Memcached]安装
查看memcached信息 $ brew info memcached memcached: stable 1.5.22 (bottled), HEAD High performance, distr ...
- Git分支管理介绍
分支管理 软件的版本控制以及分支管理贯穿于整个软件产品的生命周期,日常的项目管理对于开发团队能否有节奏且顺利的交付软件也很重要.本分支管理和版本控制规范主要分为3个部分,即分支管理规范.版本号规范.需 ...