java – Spring @Configuration运行时注入

在我的非Boot
Spring 5项目中,我需要手动注册并初始化一些bean.之后我想在上下文中添加一个@Configuration类,它从外部lib导入一个配置:

@Configuration
@Import(ExtLibConfig.class)
public class MyExtLibConfig {

  @Bean
  public ExtLibBean extLibBean() {
   return ExtLibBean.builder().build();
  }

}

ExtLibConfig有很多自己的@ComponentScan和@Import,我希望它们都能自动配置,包括我的ExtLibBean.

是否有可能在运行时这样做?外部lib扫描ApplicationContext,当我添加手动注册的bean时,我需要它来执行此操作.

UPD:
关于bean注册顺序的问题不是实际的. ext lib在刷新后扫描ApplicationContext,所以我此时需要我的bean

最佳答案 解决方案是实现BeanDefinitionRegistryPostProcessor

public class MyMockBeanDefinitioRegistrynPostProcessor implements BeanDefinitionRegistryPostProcessor {

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        // registry.registerBeanDefinition(mockBeanClass, mockBeanDefinition);...

    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        // nothing to do
    }

然后将其声明为Bean:

@Configuration
public class MockBeanConfig {

    @Bean
    public MyMockBeanDefinitioRegistrynPostProcessor mockBeanDefinitionPp() {
        return new MyMockBeanDefinitioRegistrynPostProcessor();
    }

}

并将其添加到上下文中:

AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();

context.register(MockBeanConfig.class);
context.register(MyExtLibConfig.class);

context.refresh();
点赞