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 staticFactoryBean preventAutowire(T bean) { return new FactoryBean () { public T getObject() throws Exception { return bean; } public Class> getObjectType() { return bean.getClass(); } public boolean isSingleton() { return true; } }; } ... @Bean static FactoryBean myBean() { return preventAutowire(new MyBean()); }