Reputation: 7911
I am writing a test for a @Configuration
class. It declares a @Bean
with an initMethod
:
@Bean(initMethod = "doSomething")
public MyBean myBean() {
// instantiation and initialization
}
The doSomething
method does a lot of work and would require a complex test setup to succeed. I want to test that the bean was initialized correctly but I don't want Spring to call the doSomething
method once the initialization is done.
My first idea was to use a BeanFactoryPostProcessor
:
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
String[] beanNames = beanFactory.getBeanNamesForType(MyBean.class);
BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanNames[0]);
// TODO: disable initMethod
}
But it seems there is no way to use BeanDefinition
to disable the initMethod
.
Am I missing something or is there another way to achieve this?
Upvotes: 0
Views: 344
Reputation: 279970
Check if the BeanDefinition
is a RootBeanDefinition
(or AbstractBeanDefinition
), then use its setInitMethodName
to set the init method to null
.
Set the name of the initializer method. The default is
null
in which case there is no initializer method.
if (beanDefinition instanceof RootBeanDefinition) {
((RootBeanDefinition) beanDefinition).setInitMethodName(null);
}
Upvotes: 3