nowszy94 nowszy94 - 3 months ago 15
Java Question

Get annotations of bean in BeanPostProcessor implementation

I'm trying to implement my own BeanPostProcessor implementation.

@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;
}
}


And this is my bean definition:

@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();
}
}


I'm trying to get annotations of bean, and proceed them somehow. I can clearly see why
user.getClass().getAnnotations()
not working, because it tries to get annotation from User class, and not annotations from bean definition. How can i get list of annotations on bean definition?

Answer

You should do something like:

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)) {
    ...

In other words even if it is @Bean method definition we can get all the info via its BeanDefinition.