如何禁用特定bean的Spring自动装配? [英] How to disable Spring autowiring for a certain bean?
本文介绍了如何禁用特定bean的Spring自动装配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
jar(外部库)中有一些类在内部使用Spring. 因此,库类的结构类似于:
There are some class in jar (external library), that uses Spring internally. So library class has structure like a:
@Component
public class TestBean {
@Autowired
private TestDependency dependency;
...
}
并且库提供用于构造对象的API:
And library provides API for constructing objects:
public class Library {
public static TestBean createBean() {
ApplicationContext context = new AnnotationConfigApplicationContext(springConfigs);
return context.getBean(TestBean);
}
}
在我的应用程序中,我有配置:
In my application, I have config:
@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已经配置好了.
But Spring should not trying to inject something, because bean is already configured.
我可以为某些bean禁用Spring自动装配吗?
Can i disable Spring autowiring for a certain bean?
推荐答案
基于@Juan的回答,创建了一个帮助程序来包装不自动接线的bean:
Based on @Juan's answer, created a helper to wrap a bean not to be autowired:
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());
}
这篇关于如何禁用特定bean的Spring自动装配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文