27. Spring源码篇之SpEL表达式之自定义解析模版

简介

其实前面文章我们已经介绍过了如何定义spring表达式的解析模版,但是那是直接使用表达式api的形式,对于使用spring的同学来说,更优雅的方式就是可以自定义一个扩展去修改

本文就是介绍如何通过Spring的扩展点修改表达式解析模版

自定义解析模版

首先AbstractBeanFactory就有有一个解析器BeanExpressionResolver,这个前面文件介绍过,默认是一个StandardBeanExpressionResolver

public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
    private BeanExpressionResolver beanExpressionResolver;
    public BeanExpressionResolver getBeanExpressionResolver() {
        return this.beanExpressionResolver;
    }
}

而StandardBeanExpressionResolver恰好也有修改解析版本的方法

public class StandardBeanExpressionResolver implements BeanExpressionResolver {
    public void setExpressionPrefix(String expressionPrefix) {
		this.expressionPrefix = expressionPrefix;
	}
	public void setExpressionSuffix(String expressionSuffix) {
		this.expressionSuffix = expressionSuffix;
	}
}

那么其实就是对BeanFactory的一个扩展,在spring中针对于BeanFactory的后置处理器就是 BeanFactoryPostProcessor

下面我们就来实现一下

@Component
public class SpElPostProcessor implements BeanFactoryPostProcessor {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        BeanExpressionResolver beanExpressionResolver = beanFactory.getBeanExpressionResolver();
        if (beanExpressionResolver instanceof StandardBeanExpressionResolver) {
            StandardBeanExpressionResolver resolver = (StandardBeanExpressionResolver) beanExpressionResolver;
            // 修改
            resolver.setExpressionPrefix("&{");
            resolver.setExpressionSuffix("}");
        }
    }
}

修改表达式模版为 &{}

测试

@ComponentScan({"com.shura"})
public class AppConfig {
}

public static void main(String[] args) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
    BeanExpressionResolver beanExpressionResolver = context.getBeanFactory().getBeanExpressionResolver();
    Object result = beanExpressionResolver.evaluate("&{appConfig}", new BeanExpressionContext(context.getBeanFactory(), null));
    System.out.println(result);
}

输出
com.shura.config.AppConfig@3e58a80e

欢迎关注,学习不迷路!

你可能感兴趣的:(spring,framework,spring,java,后端)