简体   繁体   中英

Approach: Modify Complex Data using AOP and Reflection

I have configured my spring Application as below:

 // Spring MVC controller
 @Controller
 HelloController {  

   @ResponseBody
   Student getData() {
    return student from database;
    }
 }

public Class Student {

 @Trim(device = "mob", trim=10)
 @Trim(device = "desktop", trim=100)
 String name ;

 Address address;

}

public class Address {

 @Trim(device = "mob", trim=10 )
 @Trim(device = "desktop", trim=100 )
 String addressInfo

 }

Requirements:

After the Controller returns the Student, do modification of Student object and all complex attributes inside it based on the Annotation , for example if the request was from mobile trim the student name to 10 and so on.

Approaches I can think of:

  1. Recursively iterate on fields with annotation and modify fields. Iteration on class fields every time can be hectic, as the class is complex and can nest up to n levels.

  2. Create a List of Annotated fields at server start up and when then iterate on this list and apply changes to the target object.

    I am currently struggling with both approachs. So would like to know whether there exists some prebuilt solutions or design patterns to handle such scenarios.

I actually coded the Reflection based approach and created a library some time back.

It uses reflection to identify annotation on fields and then takes the appropriate action based on the input device.

Here is the link for library https://github.com/santoshjoshi/Adaptive-Device-Data-Filtering

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM