Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn Spring @Autowired required property to false for test?

I've been using the @Required annotation up to now to ensure DI of my beans in a Spring configured application.

To enable the annotation, you need to declare a RequiredAnnotationBeanPostProcessor bean in your configuration.

In your test configuration you just don't declare it, so that if some beans are not needed you don't have to have them in your config.

I want to switch to less XML and use @Autowired annotation, but it is by default required=true, which is fine for the runtime configuration.

But I need @Autowired to be required=false for testing purpose only - while keeping it required for runtime.

Is that possible at all? I can't find a way to declaratively turn the required property to false.

cheers

like image 729
nodje Avatar asked Jul 19 '10 09:07

nodje


1 Answers

You probably solved it already but this trick might be useful for others.

As far as I understood without context:annotation-driven being present @Autowired annotations should not be processed but this is clearly not the case so I might misunderstood something.

However, I needed a quick solution... This somewhat dirty trick negates required value for all classes making optional what was required before. Adding it to my test context solved my problem but it is useful only if all autowirings are required in your business classes.

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor">
    <property name="requiredParameterValue" value="false" />
</bean>
like image 104
Peter Avatar answered Nov 08 '22 14:11

Peter