Announcement Announcement Module
Collapse
No announcement yet.
How to register BeanPostProcessor programmatically ? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to register BeanPostProcessor programmatically ?

    Hi all,

    I try to register BeanPostProcessor programmatically, but it seems that the bean is never get called. Here's my code

    Code:
    AbstractApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"context.xml"});
    
    BeanPostProcessor processor = new BeanPostProcessor()
    {
       @Override
       public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException
      {
    	System.out.println("name : " + name);
    	return bean;
      }
    			
     @Override
     public Object postProcessAfterInitialization(Object bean, String name) throws BeansException 
      {
    	System.out.println("name : " + name);
    	return bean;
      }
    };
    context.getBeanFactory().addBeanPostProcessor(processor);
    Have I done it in wrong way ?

    Any help would be greatly appreciated.

    Regards,

    Setya

  • #2
    Err, please don't tell me to register the BeanPostProcessor in the context file since I just need it during test so I want to register it programmatically.

    Regards,

    Setya

    Comment


    • #3
      Your applicationcontext is already initialized so registering it after that is useless unless you call refresh, which reloads the context.

      Why not put it in a xml file and load BOTH while testing, in production code you can simply leave it out (don't load the test-context.xml).

      Comment


      • #4
        Hi,

        It seems that using ApplicationContext I have to define BeanPostProcessor declaratively, for programmatically using XmlBeanFactory works fine.

        Anyway, basically during testing I need to override some bean returned by Spring so that I can returned mocked under my control so I can drive them without having to duplicate the context files, is through BeanPostProcessor the correct way to do it ? Or do I have some alternatives ?

        Regards,

        Setya

        Comment


        • #5
          You can always put the mocked bean in another xml file (with id the same as the original one) and load that file after the original xml file when creating the xml application context. e.g.
          Code:
          new ClassPathXmlApplicationContext(new String[]{"context.xml", "test-context-with-mock.xml"});
          This way the original bean will be overridden with the mocked one.

          Comment

          Working...
          X