![](/img/trans.png)
[英]How to disable Spring autowiring in unit tests for @Configuration/@Bean usage
[英]How to disable Spring autowiring for a certain bean?
jar(外部庫)中有一些類,它在內部使用Spring。 所以庫類的結構如下:
@Component
public class TestBean {
@Autowired
private TestDependency dependency;
...
}
並且庫提供了用於構造對象的API:
public class Library {
public static TestBean createBean() {
ApplicationContext context = new AnnotationConfigApplicationContext(springConfigs);
return context.getBean(TestBean);
}
}
在我的應用程序中,我有配置:
@Configuration
public class TestConfig {
@Bean
public TestBean bean() {
return Library.createBean();
}
}
它拋出異常: Field dependency in TestBean required a bean of type TestDependency that could not be found.
。
但Spring不應該嘗試注入一些東西,因為bean已經配置好了。
我可以禁用某個bean的Spring自動裝配嗎?
根據@Juan的回答,創建了一個幫助程序來包裝一個不能自動裝配的bean:
public static <T> FactoryBean<T> preventAutowire(T bean) {
return new FactoryBean<T>() {
public T getObject() throws Exception {
return bean;
}
public Class<?> getObjectType() {
return bean.getClass();
}
public boolean isSingleton() {
return true;
}
};
}
...
@Bean
static FactoryBean<MyBean> myBean() {
return preventAutowire(new MyBean());
}
這對我有用:
import org.springframework.beans.factory.FactoryBean;
...
@Configuration
public class TestConfig {
@Bean
public FactoryBean<TestBean> bean() {
TestBean bean = Library.createBean();
return new FactoryBean<TestBean>()
{
@Override
public TestBean getObject() throws Exception
{
return bean;
}
@Override
public Class<?> getObjectType()
{
return TestBean.class;
}
@Override
public boolean isSingleton()
{
return true;
}
};
}
}
不完全是,但您可以在自動裝配的注釋中添加required = false (@Autowired(required=false))
。 但要小心,可能會得到NullPointer異常
似乎不可能禁用特定bean的自動裝配。
所以有一些解決方法。 我們可以為目標bean創建包裝器並使用它而不是原始bean:
public class TestBeanWrapper {
private final TestBean bean;
public TestBeanWrapper(TestBean bean) {
this.bean = bean;
}
public TestBean bean() {
return bean;
}
}
@Configuration
public class TestConfig {
@Bean
public TestBeanWrapper bean() {
return new TestBeanWrapper(Library.createBean());
}
}
@RestController
public class TestController {
@Autowired
private TestBeanWrapper bean;
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.