How to dynamically modify the parameter values of annotations in JavaBean

  • 2021-08-21 20:39:22
  • OfStack

I have a requirement to modify the value of the annotation on an attribute in the Person class, for example:


public class Person {
 private int age;
 @ApiParam(access="lala")
 private String name;
 //get set  Method ignores  
}

Modifying @ ApiParam (access= "lala") to @ ApiParam (access= "fafa") can be realized after analysis, and dynamic agents are needed for operation.

The specific source code is as follows:


@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ApiParam {
 String access() default "";
}

The reflection + dynamic proxy code is as follows:


public class TestClazz {
 public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { 
 Person person = new Person();
 Field value = person.getClass().getDeclaredField("name");
 value.setAccessible(true);
 //APIParam  Yes 1 Custom annotations 
 ApiParam apiParam = (ApiParam) value.getAnnotation(ApiParam.class);
 java.lang.reflect.InvocationHandler invocationHandler = Proxy.getInvocationHandler(apiParam);
 Field memberValues = invocationHandler.getClass().getDeclaredField("memberValues");
 // Acquisition by reflection memberValues  This attribute is Map Type   All the attributes are stored. 
  memberValues.setAccessible(true);
  Map<String, Object> values = (Map<String, Object>) memberValues.get(invocationHandler);
  String val = (String) values.get("access");
 System.out.println("------ Before change :"+val);
 values.put("access", "fafa");// Modify attributes 
 System.out.println("-----------------");
 //Field value1 = person.getClass().getDeclaredField("name");
 value.setAccessible(true);
 ApiParam apiParam1 = (ApiParam) value.getAnnotation(ApiParam.class);
 System.out.println("------ After the change :"+apiParam1.access());
 // The way of dynamic proxy will not change the original class Contents of the file 
 }
}

Supplement: Java customizes annotations and implements pseudo-dynamic parameter transfer of annotations

Custom annotation to record the call log of the interface, this annotation can realize the transfer of pseudo-dynamic parameters.

1. jar packages to be introduced:


<dependencies>
 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-web</artifactId>
 </dependency>
 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-test</artifactId>
 </dependency>
<!-- test -->
 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-test</artifactId>
 </dependency>
 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-aop</artifactId>
 </dependency>
<!-- json -->
 <dependency>
 <groupId>commons-lang</groupId>
 <artifactId>commons-lang</artifactId>
 <version>2.4</version>
 </dependency>
 <dependency>
 <groupId>org.apache.commons</groupId>
 <artifactId>commons-lang3</artifactId>
 </dependency>
 <dependency>
 <groupId>commons-beanutils</groupId>
 <artifactId>commons-beanutils</artifactId>
 <version>1.8.0</version>
 </dependency>
 <dependency>
 <groupId>commons-collections</groupId>
 <artifactId>commons-collections</artifactId>
 <version>3.2.1</version>
 </dependency>
 <dependency>
 <groupId>commons-logging</groupId>
 <artifactId>commons-logging</artifactId>
 <version>1.1.1</version>
 </dependency>
 <dependency>
 <groupId>net.sf.json-lib</groupId>
 <artifactId>json-lib</artifactId>
 <version>2.4</version>
 </dependency>
 </dependencies>

2. Custom annotations:


package com.example.demo.annotation; 
import java.lang.annotation.*; 
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ApiOperationLog {
 String resourceId() default "";
 String operationType();
 String description() default "";
}

3. Define the section:


package com.example.demo.aspect; 
import com.example.demo.annotation.ApiOperationLog;
import net.sf.json.JSONObject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component; 
import java.util.HashMap;
import java.util.Map;
 
@Aspect
@Component
public class ApiOperationAspect { 
 @Pointcut("@annotation ( com.example.demo.annotation.ApiOperationLog)")
 public void apiLog() {
 }
 
 @AfterReturning(pointcut = "apiLog()")
 public void recordLog(JoinPoint joinPoint) {
  MethodSignature signature = (MethodSignature) joinPoint.getSignature();
  //  Gets the specified annotation on the method 
  ApiOperationLog annotation = signature.getMethod().getAnnotation(ApiOperationLog.class);
  //  Get the parameters in the annotation 
  String resourceId = getAnnotationValue(joinPoint, annotation.resourceId());
  String operationType = getAnnotationValue(joinPoint, annotation.operationType());
  String description = getAnnotationValue(joinPoint, annotation.description());
  System.out.println("resourceId:" + resourceId);
  System.out.println("operationType:" + operationType);
  System.out.println("description:" + description);
  //  Save the measured parameter values in the annotation to the database, and realize the function of recording the interface call log ( The following is omitted ...) 
 }
 
 /**
  *  Gets the parameter value of the dynamic parameter passed in the annotation 
  *
  * @param joinPoint
  * @param name
  * @return
  */
 public String getAnnotationValue(JoinPoint joinPoint, String name) {
  String paramName = name;
  //  Get all the parameters in the method 
  Map<String, Object> params = getParams(joinPoint);
  //  Parameter is dynamic :#{paramName}
  if (paramName.matches("^#\\{\\D*\\}")) {
   //  Get the parameter name 
   paramName = paramName.replace("#{", "").replace("}", "");
   //  Is it a complex parameter type : Object . Parameter name 
   if (paramName.contains(".")) {
    String[] split = paramName.split("\\.");
    //  Gets the contents of an object in a method 
    Object object = getValue(params, split[0]);
    //  Convert to JsonObject
    JSONObject jsonObject = JSONObject.fromObject(object);
    //  Get a value 
    Object o = jsonObject.get(split[1]);
    return String.valueOf(o);
   }
   //  Simple dynamic parameters return directly 
   return String.valueOf(getValue(params, paramName));
  }
  //  Direct return of non-dynamic parameters 
  return name;
 }
 
 /**
  *  Returns the corresponding value according to the parameter name 
  *
  * @param map
  * @param paramName
  * @return
  */
 public Object getValue(Map<String, Object> map, String paramName) {
  for (Map.Entry<String, Object> entry : map.entrySet()) {
   if (entry.getKey().equals(paramName)) {
    return entry.getValue();
   }
  }
  return null;
 }
 
 /**
  *  Gets the parameter names and values of the method 
  *
  * @param joinPoint
  * @return
  */
 public Map<String, Object> getParams(JoinPoint joinPoint) {
  Map<String, Object> params = new HashMap<>(8);
  Object[] args = joinPoint.getArgs();
  MethodSignature signature = (MethodSignature) joinPoint.getSignature();
  String[] names = signature.getParameterNames();
  for (int i = 0; i < args.length; i++) {
   params.put(names[i], args[i]);
  }
  return params;
 } 
}

4: Preparation before the test:


//  Entity class 
package com.example.demo.model; 
public class User {
 
 private Long id;
 private String name;
 private int age;
 
 public Long getId() {
  return id;
 }
 
 public void setId(Long id) {
  this.id = id;
 }
 
 public String getName() {
  return name;
 }
 
 public void setName(String name) {
  this.name = name;
 }
 
 public int getAge() {
  return age;
 }
 
 public void setAge(int age) {
  this.age = age;
 }
 
 @Override
 public String toString() {
  return "User{" +
    "id=" + id +
    ", name='" + name + '\'' +
    ", age=" + age +
    '}';
 }
} 
 
// controller Layer content 
package com.example.demo.controller; 
import com.example.demo.annotation.ApiOperationLog;
import com.example.demo.model.User;
import org.springframework.web.bind.annotation.RestController; 
@RestController
public class LoginController {
 
 @ApiOperationLog(resourceId = "#{user.id}",operationType = "SAVE",description = " Test annotations pass complex dynamic parameters ")
 public void saveUser(User user,String id){
  System.out.println(" Test annotation ...");
 }
 
 @ApiOperationLog(resourceId = "#{id}",operationType = "UPDATE",description = " Test annotations pass simple dynamic parameters ")
 public void updateUser(User user,String id){
  System.out.println(" Test annotation ...");
 }
 
}

5. Test classes:


package com.example.demo.aspect; 
import com.example.demo.DemoApplication;
import com.example.demo.controller.LoginController;
import com.example.demo.model.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = DemoApplication.class)
public class ControllerTest {
 
 @Autowired
 private LoginController loginController;
 
 @Test
 public void test(){
  User user = new User();
  user.setId(1L);
  user.setName("test");
  user.setAge(20);
  loginController.saveUser(user,"123");
  loginController.updateUser(user,"666");
 }
}

Test results:


 Test annotation ...
resourceId:1
operationType:SAVE
description: Test annotations pass complex dynamic parameters 
 Test annotation ...
resourceId:666
operationType:UPDATE
description: Test annotations pass simple dynamic parameters 

Related articles: