SpringBoot 代理对象导致的获取不到原生对象注解

在一次使用BeanPostProcessor初始化数据时,发现BeanPostProcessor总不能获取到Controller上的自定义注解。原生代码如下:


/**
 * @author Administrator
 */
@Component
@RequiredArgsConstructor
public class ResourceLoadBeanPostProcessor implements BeanPostProcessor {

    private final ResourceRepository resourceRepository;

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

        Class clazz = bean.getClass();
        // 总是不能获取到注解数据
        if (clazz.isAnnotationPresent(Resource.class)) {
            return bean;
        }
    }
}

解决方法:使用Spring自带的工具类Annotationutils


@Component
@RequiredArgsConstructor
public class ResourceLoadBeanPostProcessor implements BeanPostProcessor {

    private final ResourceRepository resourceRepository;

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

        Class clazz = bean.getClass();
            // 解决办法:使用Spring提供的工具类AnnotationUtils.findAnnotation(Class, Class)
        Resource parent = AnnotationUtils.findAnnotation(clazz, Resource.class);
        if (parent == null) {
            return bean;
        }

    }
}

你可能感兴趣的:(SpringBoot 代理对象导致的获取不到原生对象注解)