繁体   English   中英

如何以编程方式将 bean 添加到 Spring 上下文?

[英]How to add bean programmatically to Spring context?

我想从一些配置中创建自定义子上下文,并以编程方式另外添加一些 bean。

我阅读了关于BeanDefinitionRegistryPostProcessor的答案https://stackoverflow.com/a/4540762/258483 ,但不明白如何使用它。 如果我编写BeanDefinitionRegistryPostProcessor的实现,那么接下来该怎么做呢? 添加到上下文中? 但这是一个问题:如何将 bean 添加到上下文中! 如果我能够将BeanDefinitionRegistryPostProcessor添加到上下文中,那么我为什么要问如何添加 bean?

问题是我有上下文并想向其中添加 bean。

我知道我可以实例化 bean 并自动装配它们

Context#getAutowireCapableBeanFactory().createBean(klass);

但这显然只是电线类,但没有将其添加到上下文中?

Spring 5.0开始,您可以直接使用ApplicationContext动态注册您的 bean。

GenericApplicationContext ac = ....;
// example
ac.registerBean("myspecialBean", Integer.class, () -> new Integer(100));
// using BeanDefinitionCustomizer
ac.registerBean("myLazySpecialBean", Integer.class, () -> new Integer(100), (bd) -> bd.setLazyInit(true));

有关registerBean的不同 API,请参见此处的javadoc

最初是我自己在这里回答的,在这里也重复一遍。

实际上AnnotationConfigApplicationContext派生自AbstractApplicationContext ,它有空的postProcessBeanFactory方法留给覆盖

/**
 * Modify the application context's internal bean factory after its standard
 * initialization. All bean definitions will have been loaded, but no beans
 * will have been instantiated yet. This allows for registering special
 * BeanPostProcessors etc in certain ApplicationContext implementations.
 * @param beanFactory the bean factory used by the application context
 */
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
}

为了利用这一点,创建可能如下所示的AnnotationConfigApplicationContextProvider类(对于Vertx实例示例,您可以使用MyClass代替)...

public class CustomAnnotationApplicationContextProvider {
private final Vertx vertx;

public CustomAnnotationApplicationContextProvider(Vertx vertx) {
    this.vertx = vertx;
}

/**
 * Register all beans to spring bean factory
 *
 * @param beanFactory, spring bean factory to register your instances
 */
private void configureBeans(ConfigurableListableBeanFactory beanFactory) {
    beanFactory.registerSingleton("vertx", vertx);
}

/**
 * Proxy method to create {@link AnnotationConfigApplicationContext} instance with no params
 *
 * @return {@link AnnotationConfigApplicationContext} instance
 */
public AnnotationConfigApplicationContext get() {
    return new AnnotationConfigApplicationContext() {

        @Override
        protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
            super.postProcessBeanFactory(beanFactory);
            configureBeans(beanFactory);
        }
    };
}

/**
 * Proxy method to call {@link AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(DefaultListableBeanFactory)} with our logic
 *
 * @param beanFactory bean factory for spring
 * @return
 * @see AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(DefaultListableBeanFactory)
 */
public AnnotationConfigApplicationContext get(DefaultListableBeanFactory beanFactory) {
    return new AnnotationConfigApplicationContext(beanFactory) {

        @Override
        protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
            super.postProcessBeanFactory(beanFactory);
            configureBeans(beanFactory);
        }
    };
}

/**
 * Proxy method to call {@link AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(Class[])} with our logic
 *
 * @param annotatedClasses, set of annotated classes for spring
 * @return
 * @see AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(Class[])
 */
public AnnotationConfigApplicationContext get(Class<?>... annotatedClasses) {
    return new AnnotationConfigApplicationContext(annotatedClasses) {

        @Override
        protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
            super.postProcessBeanFactory(beanFactory);
            configureBeans(beanFactory);
        }
    };
}

/**
 * proxy method to call {@link AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(String...)} with our logic
 *
 * @param basePackages set of base packages for spring
 * @return
 * @see AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(String...)
 */
public AnnotationConfigApplicationContext get(String... basePackages) {
    return new AnnotationConfigApplicationContext(basePackages) {

        @Override
        protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
            super.postProcessBeanFactory(beanFactory);
            configureBeans(beanFactory);
        }
    };
}
}

在创建ApplicationContext时,您可以使用

Vertx vertx = ...; // either create or for vertx, it'll be passed to main verticle
ApplicationContext context = new CustomAnnotationApplicationContextProvider(vertx).get(ApplicationSpringConfig.class);

我在当前的应用程序中使用它,因为我已经有一个要注册的对象。 我可以将applicationContext作为 bean 注入。

private void registerAsBean(
  ApplicationContext injectedApplicationContext, 
  MyClass objectToRegisterAsBean, 
  String beanName) {

    AutowireCapableBeanFactory beanFactory = 
      injectedApplicationContext.getAutowireCapableBeanFactory();
    beanFactory.initializeBean(objectToRegisterAsBean, beanName);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM