首页 > 解决方案 > 如何向方法运行时添加注释?春季AOP

问题描述

我对接口中的注释方法有疑问

public interface CsvImportService {

    @Import
    void importFile(Long userId, String organizationId, MultipartFile file, String charset) throws Exception;
}

接口的实现

@Service
public class CsvImportServiceImpl implements CsvImportService {

    @Override
    public void importFile(Long userId, String organizationId, MultipartFile file, String charset) {
        ...
    }
 }

我试图通过 Spring AOP 处理它

@Slf4j
@Aspect
@Component
public class ImportAspect {

    @AfterReturning(pointcut = "@annotation(com.backend.annotations.Import)")
    public void handleImport(JoinPoint joinPoint) throws Throwable {
        LOGGER.info("handle");
    }
}

但是发现注解不去impl,所以才意识到要在实现方法中添加注解,开始写BPP

@Component
public class ImportAnnotationBeanPostProcessor implements BeanPostProcessor {

    Map<String, Class<?>> map = new HashMap<>();
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        Class<?> beanClass = bean.getClass();
        if (CsvImportService.class.isAssignableFrom(beanClass)) {
            map.put(beanName, beanClass);
        }
        return bean;
    }

    @SneakyThrows
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> beanClass = map.get(beanName);
        if (beanClass != null) {
            for (Method declaredMethod : CsvImportService.class.getDeclaredMethods()) {
                if (declaredMethod.isAnnotationPresent(Import.class)) {
                    Method importMethod = beanClass.getDeclaredMethod(declaredMethod.getName(), declaredMethod.getParameterTypes());
                    //TODO Add annotation to method
                }
            }
        }
        return bean;
    }
}

并且没有找到给方法加注解的反射方法。我该怎么做?

标签: javaspring

解决方案


推荐阅读