Spring SpEL 的使用

链接: 如何优雅记录日志.

链接: SpEL你感兴趣的实现原理浅析spring-expression.

链接: spEL—基础语法+注解中动态调用Bean方法.

Spring EL

Spring 3 提供了一个非常强大的功能:Spring EL
SpEL 在 Spring 产品中是作为表达式求值的核心基础模块
它本身是可以脱离 Spring 独立使用的。

举个例子:

public static void main(String[] args) {
    
    
        Order order = new Order();
        order.setPurchaseName("张三");
       
        // 不配置模板解析
        String paramName =  "#root.purchaseName";
        SpelExpressionParser parser = new SpelExpressionParser();
        Expression expression = parser.parseExpression(paramName);
        System.out.println(expression.getValue(order));
        
		// 定义模板解析
        paramName =  "新增配置参数,code: #{#root.purchaseName}";
        //定义模板。默认是以#{开头,以#结尾
        TemplateParserContext PARSER_CONTEXT = new TemplateParserContext();
        SpelExpressionParser parser1 = new SpelExpressionParser();
        Expression expression1 = parser1.parseExpression(paramName,PARSER_CONTEXT);
        System.out.println(expression1.getValue(order));
}

spring中调用自定义方法

SpEL支持使用@符号来引用Bean。
在引用Bean时需要使用BeanResolver接口来查找Bean,
Spring会提供BeanFactoryResolver的实现。
@RestController("AopController")
public class AopController implements BeanFactoryAware {
    
    

    //获取到Spring容器的beanFactory对象
    private BeanFactory beanFactory;

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
    
    
        this.beanFactory = beanFactory;
    }

    @GetMapping("spel")
    public String spel() {
    
    
        Order order = new Order();
        order.setPurchaseName("张三");
        order.setDeliveryOrderNo("100000001"); 
        // 自定义方法
        String spELString =  "新增配置参数,code: #{@AopController.test(#order.purchaseName)}";
        //定义模板。默认是以#{开头,以#结尾
        TemplateParserContext PARSER_CONTEXT = new TemplateParserContext();
        ExpressionParser parser = new SpelExpressionParser();
        StandardEvaluationContext context = new StandardEvaluationContext();
        //填充evaluationContext对象的`BeanFactoryResolver`。
        context.setBeanResolver(new BeanFactoryResolver(beanFactory));
        context.setVariable("order",order);
        // 构建表达式
        Expression expression = parser.parseExpression(spELString,PARSER_CONTEXT );
        // 解析
        String value = expression.getValue(context, String.class);
        return value;
    }

    public String test(String Str){
    
    
        System.out.println("自定义方法:"+Str);
        return "自定义方法";
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41604890/article/details/122998060
今日推荐