如何将Spring @Autowired必需属性转为false进行测试? [英] How to turn Spring @Autowired required property to false for test?

查看:104
本文介绍了如何将Spring @Autowired必需属性转为false进行测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我一直在使用@Required注释来确保在Spring配置的应用程序中对我的bean进行DI。



要启用注释,您需要在你的配置中声明一个RequiredAnnotationBeanPostProcessor bean。



在你的测试配置中你只是不要声明它,所以如果不需要一些bean,你就不必拥有它们在你的配置中。



我想切换到更少的XML并使用@Autowired注释,但它默认是必需= true,这对于运行时配置来说很好。



但我需要@Autowired才需要= false仅用于测试目的 - 同时保持运行时所需。



<这有可能吗?我找不到以声明方式将所需属性变为false的方法。



欢呼

解决方案

你可能已经解决了,但这个技巧可能对其他人有用。



据我所知,没有上下文:注释驱动存在@Autowired注释不应该被处理,但显然不是这样,所以我可能误解了一些东西。



然而,我需要一个快速的解决方案...这个有点肮脏的技巧否定了所有类的必需值,使得之前需要的是可选的。将其添加到我的测试上下文解决了我的问题,但只有在您的业务类中需要所有自动配置时它才有用。

 < bean class =org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor> 
< property name =requiredParameterValuevalue =false/>
< / bean>


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

解决方案

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>

这篇关于如何将Spring @Autowired必需属性转为false进行测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆