nod*_*dje 8 java testing spring dependency-injection
到目前为止,我一直在使用@Required注释来确保在Spring配置的应用程序中对我的bean进行DI.
要启用注释,需要在配置中声明RequiredAnnotationBeanPostProcessor bean.
在您的测试配置中,您只是不要声明它,因此如果不需要某些bean,您不必在配置中使用它们.
我想切换到更少的XML并使用@Autowired注释,但默认情况下需要= true,这对于运行时配置来说很好.
但我需要@Autowired才需要= false仅用于测试目的 - 同时保持运行时所需.
这有可能吗?我找不到以声明方式将required属性设置为false的方法.
干杯
Pet*_*ter 12
你可能已经解决了它,但这个技巧可能对其他人有用.
据我所知,没有上下文:注释驱动存在@Autowired注释不应该被处理,但显然不是这样,所以我可能误解了一些东西.
但是,我需要一个快速的解决方案...这个有点脏的技巧否定了所有类的必需值,使得之前需要的是可选的.将其添加到我的测试上下文解决了我的问题,但只有在业务类中需要所有自动配对时它才有用.
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor">
<property name="requiredParameterValue" value="false" />
</bean>
Run Code Online (Sandbox Code Playgroud)
小智 5
我制定了一个适用于JavaConfig配置的解决方案
@ContextConfiguration(initializers={DisableAutowireRequireInitializer.class})
public class TestCase {
// Some tests
}
Run Code Online (Sandbox Code Playgroud)
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());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14052 次 |
| 最近记录: |