6、Spring SPEL使用之--在Java类中使用SPEL

来源:互联网 发布:手机淘宝私人定制在哪 编辑:程序博客网 时间:2024/05/16 09:25

使用注解的方式配置属性

使用@Value可以向Bean属性,方法和构造函数中注入值。例子如下

向属性中注入值

使用@Value("#{ systemProperties['java.version'] }")@Value("#{systemEnvironment['JAVA_HOME']}")将Java版本和JAVA_HOME注入到Bean的属性中。

package com.codestd.springstudy.spel;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;@Componentpublic class SystemInfo {    @Value("#{ systemProperties['java.version'] }")    private String javaVersion;    @Value("#{systemEnvironment['JAVA_HOME']}")    private String javaHome;    public String getJavaVersion() {        return javaVersion;    }    public void setJavaVersion(String javaVersion) {        this.javaVersion = javaVersion;    }    public String getJavaHome() {        return javaHome;    }    public void setJavaHome(String javaHome) {        this.javaHome = javaHome;    }}

向方法中注入值

可以直接向字段的set方法中注入值

@Value("#{ systemProperties['java.version'] }")public void setJavaVersion(String javaVersion) {    this.javaVersion = javaVersion;}

向构造函数注入

在参数前面使用@Value注入值

public SystemInfo(@Value("#{ systemProperties['java.version'] }") String javaVersion, String javaHome) {    super();    this.javaVersion = javaVersion;    this.javaHome = javaHome;}

注入Bean

Bean配置如下

<bean id="people" class="com.codestd.springstudy.lesson03.People">    <property name="name" value="jaune" /></bean>

使用@Value("#{beanId}")注入Bean

@Value("#{people}")private People people;

测试

package com.codestd.springstudy.spel;import javax.annotation.Resource;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations={"classpath:spel/applicationContext.xml"})public class SystemInfoTest {    @Resource    private SystemInfo systemInfo;    @Test    public void testGetJavaVersion() {        System.out.println("Java Version:"+this.systemInfo.getJavaVersion());    }    @Test    public void testGetJavaHome() {        System.out.println("Java Home:"+this.systemInfo.getJavaHome());    }    @Test    public void testGetPeople(){        System.out.println(this.systemInfo.getPeople().getName());    }}

使用Expression

使用SpelExpressionParser类来实现转换,语法如下

ExpressionParser parser = new SpelExpressionParser();Expression exp = parser.parseExpression("spelStr");exp.getValue();//自动转换//exp.getValue(Class)exp.getValue(String.class);exp.getValue(Integer.class);...

获取字符串

package com.codestd.springstudy.spel;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.expression.Expression;import org.springframework.expression.ExpressionParser;import org.springframework.expression.spel.standard.SpelExpressionParser;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations={"classpath:spel/applicationContext.xml"})public class ExpressionParserTest {    ExpressionParser parser = new SpelExpressionParser();    @Test    public void test() {        Expression exp = parser.parseExpression("'Hello World'");        System.out.println(exp.getValue());    }}

获取字符串长度

Expression exp = parser.parseExpression("'Hello World'.length()");System.out.println(exp.getValue(Integer.class));

变量使用

使用SPEL表达式,获取上下文中定义的变量

StandardEvaluationContext context = new StandardEvaluationContext();context.setVariable("newName", "Mike Tesla");Expression exp = this.parser.parseExpression("#newName");String phraseStr = (String)exp.getValue(context);System.out.println(phraseStr);

使用SPEL表达式替换Bean中的Name字段的值
Inventor.class

package com.codestd.springstudy.spel;import java.util.Date;public class Inventor {    private String name;    private Date birthday;     private String nationality;    public Inventor() {        super();    }    public Inventor(String name, String nationality) {        super();        this.name = name;        this.nationality = nationality;    }    //getter and setter...}

Junit TestCase

@Testpublic void testVariables(){    Inventor tesla = new Inventor("Nikola Tesla", "Serbian");    //设置上下文    StandardEvaluationContext context = new StandardEvaluationContext(tesla);    //设置变量    context.setVariable("newName", "Mike Tesla");    //替换Inventor 中的Name字段,name和Name都可以    parser.parseExpression("Name = #newName").getValue(context);    //输出Bean中Name的值    System.out.println(tesla.getName());}

方法使用

分为下面几步
1. 初始化上下文 StandardEvaluationContext context = new StandardEvaluationContext();
2. 注册方法 registerFunction(String name, Method method)
3. 调用方法#functionName(args)

示例代码

@Testpublic void testFunction() throws Exception{    StandardEvaluationContext context = new StandardEvaluationContext();    context.registerFunction("reverseString",        StringUtils.class.getDeclaredMethod("reverse", new Class[] { String.class }));    String helloWorldReversed = parser.parseExpression(        "#reverseString('hello')").getValue(context, String.class);    System.out.println(helloWorldReversed);}//olleh

Note:在SPEL表达式中调用的方法是在上下文中注册的方法名,即示例代码中registerFunction方法的第一个参数。

模板的使用

SPEL模板可以允许字符串和SPEL表达式混合使用。

StandardEvaluationContext context = new StandardEvaluationContext();context.setVariable("newName", "Mike Tesla");Expression exp = this.parser.parseExpression("I'm #{#newName}", new TemplateParserContext());String phraseStr = (String)exp.getValue(context);System.out.println(phraseStr);//I'm Mike Tesla

TemplateParserContext定义了模板中SPEL表达式的前缀和后缀。一般为#{}。可以通过实现org.springframework.expression.common.ParserContext自定义前缀和后缀。

0 0