美文网首页
SpringBoot 代理对象导致的获取不到原生对象注解

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

作者: yuerumylove | 来源:发表于2021-12-20 16:43 被阅读0次

在一次使用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 代理对象导致的获取不到原生对象注解

      本文链接:https://www.haomeiwen.com/subject/ehezfrtx.html