如何禁用特定bean的Spring自动装配?
jar(外部库)中有一些类在内部使用Spring。因此,库类具有如下结构:
@Componentpublic class TestBean {
    @Autowired
    private TestDependency dependency;
    ...
}
库提供用于构造对象的API:
public class Library {    public static TestBean createBean() {
        ApplicationContext context = new AnnotationConfigApplicationContext(springConfigs);
        return context.getBean(TestBean);
    }
}
在我的应用程序中,我有配置:
@Configurationpublic 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已经配置好了。
我可以为某个豆禁用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());
}
以上是 如何禁用特定bean的Spring自动装配? 的全部内容, 来源链接: utcz.com/qa/430028.html
