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 spel of Spring to get custom annotation parameter values

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces how to use Spring's spel to obtain custom annotation parameter values related knowledge, the content is detailed and easy to understand, the operation is simple and fast, with a certain reference value, I believe you will have something to gain after reading this article on how to use Spring's spel to obtain custom annotation parameter values, let's take a look.

Spel gets the custom annotation parameter value 1. Note class package com.xxx.mall.order.service.component; import java.lang.annotation.*; / * Information monitoring such as insufficient inventory * Created by xdc on 15:43 on 2019-4-16 * / @ Retention (RetentionPolicy.RUNTIME) @ Target ({ElementType.METHOD}) @ Documentedpublic @ interface StockWarnCollect {/ * * customer id * / String customerId (); / * Source * / String source () / * * request type 1: details page 2: shopping cart to settle accounts 3: submit order * / String pageType ();} 2. Annotations use @ Override@StockWarnCollect (customerId = "# customerId", source = "# source", pageType = "2") public Map validateCarts (Long customerId, Set userSelectedIds, Short source, JSONArray couponInfo) {/ / omit} 3.aop to process import lombok.extern.slf4j.Slf4j;import org.apache.commons.lang.exception.ExceptionUtils;import org.apache.commons.lang3.StringUtils;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.Signature;import org.aspectj.lang.annotation.Around Import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Pointcut;import org.aspectj.lang.reflect.MethodSignature;import org.springframework.core.LocalVariableTableParameterNameDiscoverer;import org.springframework.expression.EvaluationContext;import org.springframework.expression.Expression;import org.springframework.expression.ExpressionParser;import org.springframework.expression.spel.standard.SpelExpressionParser;import org.springframework.expression.spel.support.StandardEvaluationContext;import org.springframework.stereotype.Component; import java.lang.reflect.Method / * * failed to place an order, inventory monitoring * Created by xdc on 15:45 on 2019-4-16 * / @ Aspect@Component@Slf4jpublic class StockWarnCollectAop {@ Pointcut (value = "@ annotation (com.xxx.mall.order.service.component.StockWarnCollect)") public void collectStockWarn () {} @ Around (value = "collectStockWarn ()") public Object around (ProceedingJoinPoint pjp) throws Throwable {Method targetMethod = this.getTargetMethod (pjp) StockWarnCollect stockWarnCollect = targetMethod.getAnnotation (StockWarnCollect.class); / / spel information String customerIdSpel = stockWarnCollect.customerId (); String sourceSpel = stockWarnCollect.source (); Integer pageType = null; / / operation type, pure string if (StringUtils.isNotBlank (stockWarnCollect.pageType () {pageType = Integer.valueOf (stockWarnCollect.pageType ()) } / / customer id, source resolution ExpressionParser parser = new SpelExpressionParser (); LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer (); String [] params = discoverer.getParameterNames (targetMethod); Object [] args = pjp.getArgs (); EvaluationContext context = new StandardEvaluationContext (); for (int len = 0; len)

< params.length; len++) { context.setVariable(params[len], args[len]); } Expression expression = parser.parse_Expression(customerIdSpel); Long customerId = expression.getValue(context, Long.class); expression = parser.parse_Expression(sourceSpel); Short source = expression.getValue(context, Short.class); log.info("collectStockWarn customerId:{}, source:{}", customerId, source); // 业务逻辑处理 Object result = null; try { result = pjp.proceed(); } catch (Throwable e) { log.info("collectStockWarn watchs creating order errorMsg:{}", ExceptionUtils.getStackTrace(e)); if (e instanceof MallException) { } else { // 未知错误 } throw e; } try { if (result != null) { } } catch (Exception e) { log.error("collectStockWarn process error, errorMsg:{}", ExceptionUtils.getStackTrace(e)); } return result; } /** * 获取目标方法 */ private Method getTargetMethod(ProceedingJoinPoint pjp) throws NoSuchMethodException { Signature signature = pjp.getSignature(); MethodSignature methodSignature = (MethodSignature)signature; Method agentMethod = methodSignature.getMethod(); return pjp.getTarget().getClass().getMethod(agentMethod.getName(),agentMethod.getParameterTypes()); }}spel在注解中的使用 SpEL(Spring Expression Language),即Spring表达式语言,是比JSP的EL更强大的一种表达式语言。为什么要总结SpEL,因为它可以在运行时查询和操作数据,尤其是数组列表型数据,因此可以缩减代码量,优化代码结构。个人认为很有用。 1 语法说明 1.1 SpEL 字面量: 整数:#{8} 小数:#{8.8} 科学计数法:#{1e4} String:可以使用单引号或者双引号作为字符串的定界符号。 Boolean:#{true} 1.2 SpEL引用bean , 属性和方法: 引用其他对象:#{car} 引用其他对象的属性:#{car.brand} 调用其它方法 , 还可以链式操作:#{car.toString()} 调用静态方法静态属性:#{T(java.lang.Math).PI} 1.3 SpEL支持的运算符号: 算术运算符:+,-,*,/,%,^(加号还可以用作字符串连接) 比较运算符:< , >

, =, > =

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