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.。
Field dependency in TestBean required a bean of type TestDependency that could not be found.
但是Spring不应该尝试注入某些东西,因为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()); }