The usage scenario of java reflection in the project

Java reflection is a powerful programming technology that can dynamically obtain and manipulate information such as classes, objects, methods, etc. at runtime. In Spring Boot projects, Java reflection is usually used in the following situations:

  1. Dependency Injection (DI) and Inversion of Control (IoC): The Spring Boot framework uses reflection to automatically inject dependent objects and perform inversion of control. For example, the @Autowired annotation is automatically injected through reflection.

  2. Bean instantiation: The Spring Boot framework uses reflection to instantiate Bean objects. For example, the @Bean annotation realizes the instantiation and initialization of Bean through reflection.

  3. AOP programming: The Spring Boot framework uses reflection to implement aspect-oriented programming (AOP). For example, the @Aspect annotation implements AOP through reflection.

  4. Database access: The Spring Boot framework uses reflection to implement ORM (Object Relational Mapping) frameworks such as Spring Data JPA. Reflection technology can automatically generate SQL statements according to the annotation information of entity classes, so as to realize data access.

  5. Configuration reading: The Spring Boot framework uses reflection to read information in configuration files. For example, the @ConfigurationProperties annotation implements configuration reading through reflection.

  6. Dynamic proxy: The Spring Boot framework uses reflection to implement dynamic proxy, thereby realizing functions such as transaction management and cache management. For example, the @Transactional annotation implements dynamic proxy through reflection.

  7. Attribute editor: The Spring Boot framework uses reflection to implement the attribute editor, thereby realizing the editing and conversion of JavaBean attributes. For example, the @InitBinder annotation implements property editors through reflection.

  8. Annotation processor: The Spring Boot framework uses reflection to implement annotation processors to implement custom annotations and annotation processing logic. For example, the @RequestMapping annotation implements annotation processors through reflection.

  9. Method interceptor: The Spring Boot framework uses reflection to implement method interceptors, so as to implement operations such as pre-, post-, and exception handling of methods. For example, the HandlerInterceptor interface implements method interceptors through reflection.

In short, Java reflection has a very wide range of application scenarios in Spring Boot projects, and can be used to implement functions such as dependency injection, AOP programming, database access, dynamic proxy, configuration reading, property editor, annotation processor, and method interceptor. When using reflection, you need to pay attention to security and performance issues to avoid unnecessary performance overhead and security risks.

Here are some specific examples:

  • Dependency Injection: Use reflection to automatically inject dependent objects.
@Service
public class UserServiceImpl implements UserService {
    
    

    @Autowired
    private UserDao userDao;

    // ...
}

In this example, the @Autowired annotation will use reflection to automatically inject the UserDao object into the UserServiceImpl class.

  • AOP programming: using reflection to implement aspect logic.
@Aspect
@Component
public class LogAspect {
    
    

    @Pointcut("execution(* com.example.springbootdemo.controller.*.*(..))")
    public void logPointcut() {
    
    }

    @Around("logPointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
    
    
        // 使用反射获取方法信息
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        String methodName = method.getName();
        Class<?> targetClass = method.getDeclaringClass();

        // ...
    }
}

In this example, the @Aspect annotation will use reflection to obtain information about the pointcut method for processing in the aspect logic.

  • Database access: Implement an ORM framework using reflection.
@Entity
@Table(name = "users")
public class User {
    
    

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "name")
    private String name;

    // ...
}

In this example, @Entity, @Table, @Id, @GeneratedValue, and @Column annotations will use reflection to generate corresponding SQL statements for data access.

  • Configuration reading: using reflection to implement configuration reading
@Configuration
@ConfigurationProperties(prefix = "myapp")
public class AppConfig {
    
    

    private String version;

    private String environment;

    // ...

    public String getVersion() {
    
    
        return version;
    }

    public void setVersion(String version) {
    
    
        this.version = version;
    }

    public String getEnvironment() {
    
    
        return environment;
    }

    public void setEnvironment(String environment) {
    
    
        this.environment = environment;
    }

    // ...
}

In this example, the @ConfigurationProperties annotation will use reflection to read the information in the configuration file and map it to the properties of the AppConfig class.

  • Dynamic Proxy: Implementing Dynamic Proxy Using Reflection
@Service
public class UserServiceImpl implements UserService {
    
    

    @Autowired
    private UserDao userDao;

    @Transactional
    public User getUserById(Long id) {
    
    
        return userDao.findById(id).orElse(null);
    }

    // ...
}

In this example, the @Transactional annotation will use reflection to implement dynamic proxy to implement transaction management.

  • Method Interceptors: Implement method interceptors using reflection
@Component
public class LogInterceptor implements HandlerInterceptor {
    
    

    @Override
    public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
    
    
        // 在方法执行前执行的逻辑
        Method method = ((HandlerMethod) handler).getMethod();
        String methodName = method.getName();
        Class<?> targetClass = method.getDeclaringClass();
        // ...
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    
    
        // 在方法执行后执行的逻辑
        // ...
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {
    
    
        // 在方法执行完成后执行的逻辑
        // ...
    }
}

In this example, the LogInterceptor class implements the HandlerInterceptor interface, and uses reflection to implement the preHandle(), postHandle(), and afterCompletion() methods, thereby realizing the function of the method interceptor.

  • Annotation Processor: Implementing Annotation Processors Using Reflection
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
    
    
    String value();
}

@Controller
public class UserController {
    
    

    @MyAnnotation("getUser")
    @RequestMapping("/user")
    public String getUser(@RequestParam("id") Long id, Model model) {
    
    
        User user = userService.getUserById(id);
        model.addAttribute("user", user);
        return "user";
    }

    // ...
}
  • Property Editor: Implementing property editors using reflection
@Controller
public class UserController {
    
    

    @InitBinder
    public void initBinder(WebDataBinder binder) {
    
    
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    }

    @RequestMapping("/user")
    public String getUser(@RequestParam("id") Long id, Model model) {
    
    
        User user = userService.getUserById(id);
        model.addAttribute("user", user);
        return "user";
    }

    // ...
}

Guess you like

Origin blog.csdn.net/m0_68705273/article/details/131006947