nowszy94 nowszy94 - 4 months ago 26
Java Question

Get annotations of bean in BeanPostProcessor implementation

I'm trying to implement my own BeanPostProcessor implementation.

public class UserDetailsProcessor implements BeanPostProcessor {

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;

return bean;

public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;

And this is my bean definition:

public class HelloReactiveApplication {

public static void main(String[] args) {, args);

@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
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?


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.