【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 ...
随机推荐
- Codeforces_462_B
http://codeforces.com/problemset/problem/462/B 简单的贪心,排序即可看出来. #include<cstdio> #include<ios ...
- 使用logstash结合logback收集微服务日志
因为公司开发环境没有装elk,所以每次查看各个微服务的日志只能使用如下命令 这样子访问日志是并不方便,于是想为每个微服务的日志都用logstash收集到一个文件out中,那以后只要输出这个文件则可查看 ...
- 深入理解ASP.NET Core依赖注入
概述 ASP.NET Core可以说是处处皆注入,本文从基础角度理解一下原生DI容器,及介绍下怎么使用并且如何替换官方提供的默认依赖注入容器. 什么是依赖注入 百度百科中对 ...
- Netty学习(2):IO模型之NIO初探
NIO 概述 前面说到 BIO 有着创建线程多,阻塞 CPU 等问题,因此为解决 BIO 的问题,NIO 作为同步非阻塞 IO模型,随 JDK1.4 而出生了. 在前面我们反复说过4个概念:同步.异步 ...
- 适合产品经理的十本书 From 俞军
(转自俞军,如有侵权,请评论区留言,我会尽快删除:) 适合产品经理的十本书 俞军 入门三本书:社会心理学 阿伦森 插图第七版:特别好,适合成为“产品经理的第一本书”第一本经济学:经济学帮助人们洞察世事 ...
- tensorflow roadshow 全球巡回演讲 会议总结
非常荣幸有机会来到清华大学的李兆基楼,去参加 tensorflow的全球巡回.本次主要介绍tf2.0的新特性和新操作. 1. 首先,tensorflow的操作过程和机器学习的正常步骤一样,(speak ...
- hive on spark 编译时遇到的问题
1.官方网站下载spark 1.5.0的源码 2.根据官方编译即可. export MAVEN_OPTS="-Xmx2g -XX:MaxPermSize=512M -XX:ReservedC ...
- React中的生命周期函数
React的生命周期函数 什么是生命周期函数:生命周期函数是指在某一个时刻组件会自动调用执行的函数 Initialization:初始化 执行Constructor,初始state和props Mou ...
- [shell] shell 变量生命周期, source, export
1. shell 的派生 用户登录到Linux系统后,系统将启动一个用户shell.在这个shell中,可以使用shell命令, 或声明变量,也可以创建并运行shell脚本程序.运行shell脚本程序 ...
- PAT-1005 Spell It Right 解答(C/C++/Java/python)
1.Description: Given a non-negative integer N, your task is to compute the sum of all the digits of ...