【问题标题】:How to turn Spring @Autowired required property to false for test?如何将 Spring @Autowired 所需属性设置为 false 以进行测试?
【发布时间】:2010-07-19 09:34:29
【问题描述】:

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

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

在您的测试配置中,您只是不声明它,因此如果不需要某些 bean,您不必在配置中包含它们。

我想切换到更少的 XML 并使用 @Autowired 注解,但默认为 required=true,这对于运行时配置很好。

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

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

干杯

【问题讨论】:

    标签: java spring testing dependency-injection


    【解决方案1】:

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

    据我所知,没有 context:annotation-driven 存在 @Autowired 注释不应该被处理,但显然不是这样,所以我可能会误解一些东西。

    但是,我需要一个快速的解决方案……这个有点肮脏的技巧否定了所有类的必需值,从而使以前需要的东西成为可选的。将它添加到我的 测试上下文 解决了我的问题,但它仅在您的业务类中需要所有自动装配时才有用。

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

    【讨论】:

    • 一个精度:为了让它工作,它必须放在 之前,否则它不会被考虑在内。
    【解决方案2】:

    我制定了一个适用于 JavaConfig 配置的解决方案

    @ContextConfiguration(initializers={DisableAutowireRequireInitializer.class})
    public class TestCase {
        // Some tests
    }
    
    public class DisableAutowireRequireInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
    
    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
    
        // Register the AutowiredAnnotationBeanPostProcessor while initalizing
        // the context so we get there before any @Autowire resolution happens
        // We set the "requiredParameterValue" so that @Autowire fields are not 
        // required to be resolved. Very useful for a test context
        GenericApplicationContext ctx = (GenericApplicationContext) applicationContext;
        ctx.registerBeanDefinition(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME,
                BeanDefinitionBuilder
                    .rootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class)
                    .addPropertyValue("requiredParameterValue", false)
                    .getBeanDefinition());
    
        }
    
    }
    

    【讨论】:

      【解决方案3】:

      您可以使用与 @Required 相同的技术 - 不要在您的测试上下文中注册 AutowiredAnnotationBeanPostProcessor,而是将其保留在您的实时上下文中。

      这通常通过添加&lt;context:annotation-driven/&gt;来注册,而不是手动声明。

      【讨论】:

      • 等一下,如果你不添加 ,Spring 甚至不会检测到 @Autowired 注解,对吧?理想情况下,我想要的,但我相信很多人都面临过这个问题,是让 Spring 加载 ,即检测注释,但将默认的 @Autowired(required = true) 设置为false,这样我就不必在测试模式下注入运行时需要但无用甚至不受欢迎的依赖项。
      • @nodje:很公平,但恐怕不是这样的。
      猜你喜欢
      • 2021-12-13
      • 2014-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多