Question

I find it impossible to post-process a bean before factoryBean.getObject() is called. 'resultingBean' is a dependency of some bean that is initialized at the beginning, so that it is instantiated first. See I would need 'myBeanPostProcessor' to do something with 'myBean' before 'resultingBean' is constructed in 'MyFactoryBean'. Neither lazy-init nor depends-on helps. No matter what, 'MyFactoryBean.getObject()' is always called first.

<bean id="myBean" class="example.MyBean" />

<bean id="myBeanPostProcessor" class="example.MyBeanPostProcessor" />

<bean id="resultingBean" class="example.MyFactoryBean" depends-on="myBean"/>

Any idea how to deal with this? I chose BeanPostProcessor on purpose because this requirement should deal with setting up mocito mocks preceding junit @Before method...The problem is that setting up those mocks in @Before method is too late because you need to work with them at the time of context initialization.

There is not many ways how to do that, including ExecutionListeners, ContextLoaders, BeanFactoryPostprocessor, Runner and many others.

I'm using springockito that mocks my beans on the fly.

This is a little drawback of otherwise perfect spring test framework.

Was it helpful?

Solution

I don't really agree with using mocks like that (ie for integration tests) but I understand your problem.

You need to use the ApplicationContextAware interface which is called before InitializingBean, and BeanPostProcessor.

However Your Factory will always be called first so consider a different option like the new java style of configuration or refactor (as it seem you might have sort cyclical dependency)

Other than I need more info.

OTHER TIPS

Not sure if I understood your issue well, but can't you simply create another context file - say test-override-context.xml and redefine the beans there, the last bean with the same name is that takes effect in the context.

in your test-override-context.xml file:

<import resource="my-base-resource.xml"/>
<bean id="myBean" class="MyMockedBean">
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top