在 BeanPostProcessor 实现中获取 bean 的注释

now*_*y94 3 java spring annotations spring-boot

我正在尝试实现我自己的 BeanPostProcessor 实现。

@Component
public class UserDetailsProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof User) {
            User user = (User) bean;
            List<Annotation> beanAnnotations = Arrays.asList(user.getClass().getAnnotations());
            for (Annotation annotation : beanAnnotations) {
                UserDetails userDetails = (UserDetails) annotation;
                System.out.println(userDetails.firstName());
                System.out.println(userDetails.lastName());
            }
        }

        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的 bean 定义:

@SpringBootApplication
public class HelloReactiveApplication {

    public static void main(String[] args) {
        SpringApplication.run(HelloReactiveApplication.class, args);
    }

    @Bean
    @UserDetails(firstName = "Szymon", lastName = "Nowak")
    public User user() {
        return new User();
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试获取 bean 的注释,并以某种方式处理它们。我可以清楚地看到为什么user.getClass().getAnnotations()不工作,因为它试图从 User 类中获取注释,而不是从 bean 定义中获取注释。如何获取 bean 定义的注释列表?

Art*_*lan 5

你应该做这样的事情:

BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
BeanDefinition beanDefinition = registry.getBeanDefinition(beanName);
if (beanDefinition instanceof AnnotatedBeanDefinition) {
    if (beanDefinition.getSource() instanceof MethodMetadata) {
        MethodMetadata beanMethod = (MethodMetadata) beanDefinition.getSource();
        String annotationType = UserDetails.class.getName();
        if (beanMethod.isAnnotated(annotationType)) {
    ...
Run Code Online (Sandbox Code Playgroud)

换句话说,即使是@Bean方法定义,我们也可以通过它的BeanDefinition.