如何将Spring @Autowired必需属性变为false进行测试?

到目前为止,我一直在使用@Required注释来确保在Spring配置的应用程序中对我的bean进行DI。 要启用注释,需要在配置中声明RequiredAnnotationBeanPostProcessor bean。 在您的测试配置中,您只是不要声明它,因此如果不需要某些bean,您不必在配置中使用它们。 我想切换到更少的XML并使用@Autowired注释,但默认情况下需要= true,这对于运行时配置来说很好。 但我需要@Autowired才需要= false仅用于测试目的 - 同时保持运行时所需。 这有可能吗?我找不到以声明方式将required属性设置为false的方法。 干杯     
已邀请:
你可能已经解决了它,但这个技巧可能对其他人有用。 据我所知,没有上下文:注释驱动存在@Autowired注释不应该被处理,但显然不是这样,所以我可能误解了一些东西。 但是,我需要一个快速的解决方案...这个有点脏的技巧否定了所有类的必需值,使得之前需要的是可选的。将其添加到我的测试上下文解决了我的问题,但只有在业务类中需要所有自动配对时它才有用。
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor">
    <property name="requiredParameterValue" value="false" />
</bean>
    
我找到了适用于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());

    }

}
    
您可以使用与
@Required
相同的技术 - 不要在测试环境中注册
AutowiredAnnotationBeanPostProcessor
,而是将其保留在实时环境中。 这通常通过添加
<context:annotation-driven/>
来注册,而不是手动声明。     

要回复问题请先登录注册