Using spring to get method parameters and parameter values through aop
- 2021-11-13 01:49:56
- OfStack
Directory spring obtains method parameters and parameter values through aop, user-defined annotation section aop section annotation, parameter obtains 1, defines annotation of required section 2, annotation of method requiring section 3, defines section
spring obtains method parameters and parameter values through aop
Custom annotations
package com.xiaolc.aspect;
import java.lang.annotation.*;
/**
* @author lc
* @date 2019/9/10
*/
@Documented
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface LiCheng {
}
Sectional plane
package com.xiaolc.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
* Gets the annotation value on the method
*/
@Component
@Aspect
public class AuditAnnotationAspect {
@Around("@annotation(liCheng))")
private static Map getFieldsName(ProceedingJoinPoint joinPoint,LiCheng liCheng) throws ClassNotFoundException, NoSuchMethodException {
String classType = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
// Parameter value
Object[] args = joinPoint.getArgs();
Class<?>[] classes = new Class[args.length];
for (int k = 0; k < args.length; k++) {
if (!args[k].getClass().isPrimitive()) {
// Gets the encapsulated type instead of the underlying type
String result = args[k].getClass().getName();
Class s = map.get(result);
classes[k] = s == null ? args[k].getClass() : s;
}
}
ParameterNameDiscoverer pnd = new DefaultParameterNameDiscoverer();
// Gets the specified method, the 2 You can not pass a parameter, but in order to prevent overloading, you still need to pass in the type of the parameter
Method method = Class.forName(classType).getMethod(methodName, classes);
// Parameter name
String[] parameterNames = pnd.getParameterNames(method);
// Pass map Package parameters and parameter values
HashMap<String, Object> paramMap = new HashMap();
for (int i = 0; i < parameterNames.length; i++) {
paramMap.put(parameterNames[i], args[i]);
System.out.println(" Parameter name: "+parameterNames[i]+"\n Parameter value "+args[i]);
}
return paramMap;
}
private static HashMap<String, Class> map = new HashMap<String, Class>() {
{
put("java.lang.Integer", int.class);
put("java.lang.Double", double.class);
put("java.lang.Float", float.class);
put("java.lang.Long", Long.class);
put("java.lang.Short", short.class);
put("java.lang.Boolean", boolean.class);
put("java.lang.Char", char.class);
}
};
}
aop section annotation, parameter acquisition
In the work will often use aop, here will use aop basic method, access to the tangent point used in the acquisition parameters, annotations do a sample.
1. Define the annotations that need to be cut
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AnnDemo {
String value();
boolean isAop() default true;
}
2. Mark annotations in the method that needs to be cut
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private OrderService orderService;
@RequestMapping("/all")
@AnnDemo(value = "all",isAop = false)
public List<TbOrder> findAll() {
List<TbOrder> list = orderService.getOrderList();
return list;
}
@RequestMapping("/page")
@AnnDemo(value = "page")
public List<TbOrder> findPage(@RequestParam("username") String username) {
List<TbOrder> listPage = orderService.getOrdersListPage();
return listPage;
}
}
3. Define the section
Obtain tangent point annotations, methods and parameters in tangent plane
@Aspect
@Component
public class AspectDemo {
@Pointcut(value = "execution(* com.yin.freemakeradd.controller..*(..))")
public void excetionMethod() {}
@Pointcut(value = "execution(* com.yin.freemakeradd.controller..*(..)) && @annotation(AnnDemo)")
public void excetionNote() { }
@Before("excetionMethod()")
public void testBefore(JoinPoint joinPoint) {
System.out.println("---------------------------- Pre-notification ---");
Object[] args = joinPoint.getArgs();
for (Object arg : args) {
System.out.println(arg);
}
}
@Around(value = "execution(* com.yin.freemakeradd.controller..*(..)) && @annotation(AnnDemo)")
public Object testBeforeNote(ProceedingJoinPoint joinPoint) throws Throwable {
// Signature with the most notifications used
Signature signature = joinPoint.getSignature();
MethodSignature msg=(MethodSignature) signature;
Object target = joinPoint.getTarget();
// Method to get annotation annotation
Method method = target.getClass().getMethod(msg.getName(), msg.getParameterTypes());
// Get annotations through methods
AnnDemo annotation = method.getAnnotation(AnnDemo.class);
Object proceed;
// Get parameters
Object[] args = joinPoint.getArgs();
System.out.println(annotation.value());
System.out.println(annotation.isAop());
for (Object arg : args) {
System.out.println(arg);
}
if (Objects.isNull(annotation) || !annotation.isAop()) {
System.out.println(" No processing required ");
proceed = joinPoint.proceed();
}else {
System.out.println(" Enter aop Judge ");
proceed = joinPoint.proceed();
if(proceed instanceof List){
List proceedLst = (List) proceed;
if(!CollectionUtils.isEmpty(proceedLst)){
TbOrder tbOrder = new TbOrder();
tbOrder.setPaymentType("fffffffffffffffffff");
ArrayList<TbOrder> tbOrderLst = new ArrayList<>();
tbOrderLst.add(tbOrder);
return tbOrderLst;
}
}
System.out.println(proceed);
}
return proceed;
}
}