4

I'm trying to create a BeanPostProcessor for registering some values to a Map.

The BeanPostProcessor works fine if I'm create the bean instance via xml definition, but if I change the bean definition to @Configuration it is not working.

PostProcessor

public class InstantiationTracingBeanPostProcessor implements BeanPostProcessor {

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

  public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
      System.out.println("Bean '" + beanName );
      return bean;
  }
}

Bean Configuration

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;

@org.springframework.context.annotation.Configuration
public class Configuration {
    @Bean
    public @Qualifier("InstantiationTracingBeanPostProcessor")
    InstantiationTracingBeanPostProcessor activitiConfigurationBeanPostProcessor() {
        return new InstantiationTracingBeanPostProcessor();
    }
}

Component scan Configuration

<context:component-scan base-package="xyz.config"/>
<context:annotation-config/>

The application just hangs if I use the above configuration. But if I use xml based configuration as given below it works fine.

<bean class="xyz.bean.InstantiationTracingBeanPostProcessor"/>

What am I doing wrong here?

micha
  • 47,774
  • 16
  • 73
  • 80
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531

2 Answers2

6

I got a solution to this after asking another question in spring forum.

The bean factory method should be defined as a static method to make it work.

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
5

I thought the way to do this was to annotate your BeanPostProcessor with Component:

@Component
public class InstantiationTracingBeanPostProcessor implements BeanPostProcessor {
    //...
}

Which would be automatically handled by Spring during component scan (so no need to add a @Bean-annotated method to the configuration).

kschneid
  • 5,626
  • 23
  • 31