问题:
今天遇到@Value注解,一会用@Value(#{})、一会用@Value(${}),并感觉有点不太适应,特查询资料,@Value注解也会用到相关的spel表达式,帮助和我一样有困惑的小伙伴解疑答惑。(细节最重要)
目录
1.在Spring中我们经常会使用@Value注解,它有两种配置形式,都可以将外部值动态注入到Bean中
1.在Spring中我们经常会使用@Value注解,它有两种配置形式,都可以将外部值动态注入到Bean中
- @Value(#{}) 可以获取对应属性文件中定义的属性值。(主要通过spring的配置文件)
- @Value(${}) 表示为spel表达式通常用来获取bean的属性,或者调用bean的某个方法。(可以用到spel表达式)
2.基于配置文件的注入,用到的是@Value(${})
在application.yml文件中配置相关的端口
在相关的Java中使用
3.基于非配置文件注入 @Value{#{}}
SpEL表达式:
SpEL表达式语言是一种表达式语言,是一种可以与一个基于spring的应用程序中的运行时对象交互的东西。有点类似于ognl表达式。总得来说SpEL表达式是一种简化开发的表达式,通过使用表达式来简化开发,减少一些逻辑、配置的编写。
---------------
注入普通字符串
注入操作系统属性
#{systemProperties['user.language']}来设置值,用来检索用户语言系统的属性。
EL预定义变量:systemProperties和systemEnvironment
注入表达式结果
//其他bean,自定义名称为 myBeans
@Component("myBeans")
public class OtherBean {
@Value("OtherBean的NAME属性")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
注入URL资源
4.Spel表达式用法及语法
常规SpEL有三种用法:
- 在注解@Value中使用
- 在XML配置中使用
XML配置用在Spring的applicationContext.xml配置文件内的<bean>元素上,用法如下:
<bean id="xxx" class="com.java.XXXXX.xx">
<!-- 同@Value,#{}内是表达式的值,可放在property或constructor-arg内 -->
<property name="arg" value="#{表达式}">
</bean>
- 在代码中创建Expression对象,利用Expression对象来执行SpEL
public static void main(String[] args) {
//创建ExpressionParser解析表达式
ExpressionParser parser = new SpelExpressionParser();
//SpEL表达式语法设置在parseExpression()入参内
Expression exp = parser.parseExpression("表达式");
//执行SpEL表达式,执行的默认Spring容器是Spring本身的容器:ApplicationContext
Object value = exp.getValue();
/**也可以使用非Spring的ApplicationContext容器,则用下面的方法*/
//创建一个虚拟的容器EvaluationContext
StandardEvaluationContext ctx = new StandardEvaluationContext();
//向容器内添加bean
BeanA beanA = new BeanA();
ctx.setVariable("bean_id", beanA);
//setRootObject并非必须;一个EvaluationContext只能有一个RootObject,引用它的属性时,可以不加前缀
ctx.setRootObject(XXX);
//getValue有参数ctx,从新的容器中根据SpEL表达式获取所需的值
Object value = exp.getValue(ctx);
}
直接量表达式
//@Value("Hello World") 或者用直接字符串
@Value("#{'Hello World'}")
String word; //变量word赋值直接量:字符串"Hello World"
//注入list
@Value("7,2,3,5,1")
private List<Integer> fList;
直接使用java代码
如在SpEL中直接试用new/instance of,像写Java代码一样。
注意:在SpEL中直接使用某个类名时,此类必须是java.lang 包中的类,才可以在SpEL中省略包名;否则需要写全名
Expression exp = parser.parseExpression("new Spring('Hello World')");
使用T(Type)
使用“T(Type)”来表示java.lang.Class类的实例,即如同java代码中直接写类名。同样,只有java.lang 下的类才可以省略包名。此方法一般用来引用常量或静态方法
parser.parseExpression("T(Integer).MAX_VALUE"); //等同于java代码中的:Integer.MAX_VALUE
变量
获取容器内的变量,可以使用“#bean_id”来获取。有两个特殊的变量,可以直接使用。
- #this 使用当前正在计算的上下文
- #root 引用容器的root对象,即applicationContext本身
//从ctx容器内,获取rootObject,并转换为String类型
String result1 = parser.parseExpression("#root").getValue(ctx, String.class);
//在ctx容器内,设置abc的值为"abcdef"
String s = new String("abcdef");
ctx.setVariable("abc",s);
//取id为abc的bean,然后调用其中的substring方法,得到结果赋值给result2
String result2 = parser.parseExpression("#abc.substring(0,1)").getValue(ctx, String.class);
方法调用
SpEL的方法调用与直接编写Java代码没有什么区别。具体可见上例abc.substring(0,1)与java代码"abcdef".substring(0,1)效果一样
SpEL也可以自定义方法,如下:( “registerFunction”和“setVariable”都可以注册自定义函数,但是两个方法的含义不一样,推荐使用“registerFunction”方法注册自定义函数。)
//创建ctx容器
StandardEvaluationContext ctx = new StandardEvaluationContext();
//获取java自带的Integer类的parseInt(String)方法
Method parseInt = Integer.class.getDeclaredMethod("parseInt", String.class);
//将parseInt方法注册在ctx容器内
ctx.registerFunction("parseInt", parseInt);
//再将parseInt方法设为parseInt2
ctx.setVariable("parseInt2", parseInt);
//创建ExpressionParser解析表达式
ExpressionParser parser = new SpelExpressionParser();
//SpEL语法,比对两个方法执行完成后,结果是否相同
String expreString = "#parseInt('2') == #parseInt2('3')";
Expression expression = parser.parseExpression(expreString);
return expression.getValue(ctx, Boolean.class); //执行结果为false
/** 如果String expreString = "#parseInt('3') == #parseInt2('3')",执行结果为true */
/** 可见SpEL正常执行*/
运算符表达式
算数表达式(“1+2-3*4/2″)
比较表达式(“1>2”)
逻辑表达式(“2>1 and (!true or !false)”)
赋值表达式(“#variableName=value”)
三目表达式(“表达式1?表达式2:表达式3”)
正则表达式(“123′ matches ‘\\d{3}”)
等运算符,都可以直接放在SpEL中,执行结果为运算符表达式的结果
Elvis运算符
是三目运算符的特殊写法,可以避免null报错的情况
//SpEL可简写为:
name?:"other"
//等同于java代码
name != null? name : "other"
安全保证
为了避免操作对象本身可能为null,取属性时报错,可以使用SpEL检验语法
语法: “对象?.变量|方法”
//SpEL表达式简写
list?.length
//等同于java代码
list == null? null: list.length
当对象为null时,直接返回“null”,不会抛出NullPointerException
集合定义
使用“{表达式,……}”定义List,如“{1,2,3}”
//SpEL的@Value注解设置List
@Value("1,2,3")
private List<Integer> f1;
@RequestMapping(value = "/a", method = RequestMethod.POST)
public List<Integer> a() throws NoSuchMethodException {
//SpEL
List<Integer> result1 = parser.parseExpression("{1,2,3}").getValue(List.class);
//等同于如下java代码
Integer[] integer = new Integer[]{1,2,3};
List<Integer> result2 = Arrays.asList(integer);
return result1;
}
对于字面量表达式列表,SpEL会使用java.util.Collections.unmodifiableList 方法将列表设置为不可修改。
集合访问
SpEL目前支持所有集合类型和字典类型的元素访问
语法:“集合[索引]”、“map[key]”
EvaluationContext context = new StandardEvaluationContext();
//即list.get(0)
int result1 = parser.parseExpression("{1,2,3}[0]").getValue(int.class);
//list获取某一项
Collection<Integer> collection = new HashSet<Integer>();
collection.add(1);
collection.add(2);
context.setVariable("collection", collection);
int result2 = parser.parseExpression("#collection[1]").getValue(context, int.class);
//map获取
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("a", 1);
context.setVariable("map", map);
int result3 = parser.parseExpression("#map['a']").getValue(context, int.class);
集合修改
可以使用赋值表达式或Expression接口的setValue方法修改;
//赋值语句
int result = parser.parseExpression("#array[1] = 3").getValue(context, int.class);
//serValue方法
parser.parseExpression("#array[2]").setValue(context, 4);
集合选择
通过一定的规则对及格进行筛选,构造出另一个集合
语法:“(list|map).?[选择表达式]”
选择表达式结果必须是boolean类型,如果true则选择的元素将添加到新集合中,false将不添加到新集合中。
parser.parseExpression("#collection.?[#this>2]").getValue(context, Collection.class);
集合投影
根据集合中的元素中通过选择来构造另一个集合,该集合和原集合具有相同数量的元素
语法:“SpEL使用“(list|map).![投影表达式]”
public class Book {
public String name; //书名
public String author; //作者
public String publisher; //出版社
public double price; //售价
public boolean favorite; //是否喜欢
}
public class BookList {
@Autowired
protected ArrayList<Book> list = new ArrayList<Book>() ;
protected int num = 0;
}
将BookList的实例映射为bean:readList,在另一个bean中注入时,进行投影
//从readList的list下筛选出favorite为true的子集合,再将他们的name字段投为新的list
@Value("#{list.?[favorite eq true].![name]}")
private ArrayList<String> favoriteBookName;