Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use aop+spel expressions to play with different sections

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Editor to share with you how to use aop+spel expressions to play with different aspects. I hope you will get something after reading this article. Let's discuss it together.

What is spel?

Spring expression language (SpEL for short) is a powerful expression language that supports querying and manipulating object graphs at run time.

The language syntax is similar to Unified EL, but provides other functions, most notably method calls and basic string templates.

In addition, it is not directly bound to Spring, but can be used independently

What features can spel support?

Literal expression

Boolean operator and relational operator

Common expression

Class expression

Access properties, arrays, lists, and mappings

Method call

Relational operator

Distribution

Call constructor

Bean reference

Array construction

Inline list

Inline Map

Ternary operator

Variable

User-defined featur

Set projection

Set selection

Template expression

The above spel syntax can be looked up at https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#expressions-language-ref at the following link

Basic flow of spel parsing

The general steps like the figure below are as follows

Create a parser

Analytic expression

Construction context

Evaluation

Introduction of spel Core Interface

1 、 org.springframework.expression.ExpressionParser

Expression parser, whose main function is to convert string expressions into Expression objects. Support for parsing templates and standard expression strings

Its default implementation is

Org.springframework.expression.spel.standard.SpelExpressionParser

2 、 org.springframework.expression.EvaluationContext

Spel calculates the "context" of the expression value, and this Context object can contain multiple objects, but only one root (root) object. When an expression contains a variable, spel evaluates the expression based on the value of the variable in EvaluationContext. You can use the setRootObject method to set the root object, the setVariable method to register custom variables, and registerFunction to register custom functions.

Its default implementation is

Org.springframework.expression.spel.support.StandardEvaluationContext

3 、 org.springframework.expression.Expression

Represents an expression that gets the expression value according to the context through the getValue method

Its default implementation is

Org.springframework.expression.spel.standard.SpelExpressionspel official documentation

Https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#expressions

Text

Before a brief introduction to spel, let's demonstrate it through a small example below.

This small example is mainly implemented through AOP+SPEL. The example scenario is: when the product price is greater than 10:00, put it into the local cache and print out the locally cached value through a timer.

1. The core code of business logic implementation

@ Servicepublic class ProductServiceImpl implements ProductService {@ Autowired private ProductMockDao productMockDao; @ Override @ LocalCacheable (key = "# product.id", condition = "# product.price ge 10") public Product save (Product product) {return productMockDao.save (product);}}

2. Aop section compilation

@ Component@Aspectpublic class CacheAspect {@ Around ("@ annotation (localCacheable)") public Object around (ProceedingJoinPoint pjp, LocalCacheable localCacheable) throws Throwable {MethodSignature methodSignature = (MethodSignature) pjp.getSignature (); Method method = methodSignature.getMethod (); Object [] args = pjp.getArgs (); Object result = pjp.proceed (); String key = pjp.getTarget (). GetClass (). GetName () + "_" + method.getName () + "_" + args.length If (! StringUtils.isEmpty (localCacheable.key () {key = SpELParserUtils.parse (method,args,localCacheable.key (), String.class);} System.out.println ("key:" + key); if (! StringUtils.isEmpty (localCacheable.condition () {boolean condition = SpELParserUtils.parse (method,args,localCacheable.condition (), Boolean.class) If (condition) {LocalCache.INSTANCE.put (key,result);}} else {LocalCache.INSTANCE.put (key,result);} return result;}}

3. Parsing spel core tool classes

@ Slf4jpublic final class SpELParserUtils {private static final String EXPRESSION_PREFIX = "# {"; private static final String EXPRESSION_SUFFIX = "}"; / * expression parser * / private static ExpressionParser expressionParser = new SpelExpressionParser (); / * parameter name parser, used to get the parameter name * / private static DefaultParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer () Private SpELParserUtils () {} / * * parse spel expression * * @ param method method * @ param args parameter value * @ param spelExpression expression * @ param clz return type of result * @ param defaultResult default result * @ return result after executing spel expression * / public static T parse (Method method, Object [] args, String spelExpression, Class clz T defaultResult) {String [] params = parameterNameDiscoverer.getParameterNames (method) EvaluationContext context = new StandardEvaluationContext (); / / set the context variable for (int I = 0; I

< params.length; i++) { context.setVariable(params[i], args[i]); } T result = getResult(context,spelExpression,clz); if(Objects.isNull(result)){ return defaultResult; } return result; } /** * 解析spel表达式 * * @param method 方法 * @param args 参数值 * @param spelExpression 表达式 * @param clz 返回结果的类型 * @return 执行spel表达式后的结果 */ public static T parse(Method method, Object[] args, String spelExpression, Class clz) { String[] params = parameterNameDiscoverer.getParameterNames(method); EvaluationContext context = new StandardEvaluationContext(); //设置上下文变量 for (int i = 0; i < params.length; i++) { context.setVariable(params[i], args[i]); } return getResult(context,spelExpression,clz); } /** * 解析spel表达式 * * @param param 参数名 * @param paramValue 参数值 * @param spelExpression 表达式 * @param clz 返回结果的类型 * @return 执行spel表达式后的结果 */ public static T parse(String param, Object paramValue, String spelExpression, Class clz) { EvaluationContext context = new StandardEvaluationContext(); //设置上下文变量 context.setVariable(param, paramValue); return getResult(context,spelExpression,clz); } /** * 解析spel表达式 * * @param param 参数名 * @param paramValue 参数值 * @param spelExpression 表达式 * @param clz 返回结果的类型 * @param defaultResult 默认结果 * @return 执行spel表达式后的结果 */ public static T parse(String param, Object paramValue,String spelExpression, Class clz, T defaultResult) { EvaluationContext context = new StandardEvaluationContext(); //设置上下文变量 context.setVariable(param, paramValue); T result = getResult(context,spelExpression,clz); if(Objects.isNull(result)){ return defaultResult; } return result; } /** * 获取spel表达式后的结果 * * @param context 解析器上下文接口 * @param spelExpression 表达式 * @param clz 返回结果的类型 * @return 执行spel表达式后的结果 */ private static T getResult(EvaluationContext context,String spelExpression, Class clz){ try { //解析表达式 Expression expression = parse_Expression(spelExpression); //获取表达式的值 return expression.getValue(context, clz); } catch (Exception e) { log.error(e.getMessage(),e); } return null; } /** * 解析表达式 * @param spelExpression spel表达式 * @return */ private static Expression parse_Expression(String spelExpression){ // 如果表达式是一个#{}表达式,需要为解析传入模板解析器上下文 if(spelExpression.startsWith(EXPRESSION_PREFIX) && spelExpression.endsWith(EXPRESSION_SUFFIX)){ return expressionParser.parse_Expression(spelExpression,new TemplateParserContext()); } return expressionParser.parse_Expression(spelExpression); }} 4、 示例效果

After reading this article, I believe you have a certain understanding of "how to play different aspects through aop+spel expressions". If you want to know more about it, you are welcome to follow the industry information channel. Thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report