如何在Spring Boot测试中直接自动关联父应用程序上下文?

问题描述

我想直接在Spring Boot Test中直接自动关联父应用程序上下文或属于该父上下文的ConfigurableListableBeanFactory。就我而言 我正在使用Spring Boot Cloud,所以我的应用程序上下文的父应用程序上下文是bootstrap上下文。我想要它的原因是检查在bootstrap上下文中是否正确分配了在自定义引导程序配置中定义的bean。

等级依赖性:

implementation group: 'org.springframework.cloud',name: 'spring-cloud-starter',version: '2.2.5.RELEASE'

我要检查的示例豆:

public class TestBean {
}

我的自定义引导程序配置:

@Configuration
public class MyBootstrapAutoconfiguration {
  @Bean
  public TestBean myBean() {
    return new TestBean();
  }
}

spring.factories

org.springframework.cloud.bootstrap.BootstrapConfiguration=\
  com.example.demo.MyBootstrapAutoconfiguration

样本测试:

@SpringBootTest(classes = MyBootstrapAutoconfigurationTest.TestConfiguration.class)
class MyBootstrapAutoconfigurationTest {

  @Autowired
  private ApplicationContext applicationContext;

  @Autowired
  private ConfigurableListableBeanFactory configurableListableBeanFactory;

  @Test
  void test() {
    String[] beansFromAppContext = applicationContext.getBeanNamesForType(TestBean.class);
    String[] beansFromBootstrapContext = applicationContext.getParent().getBeanNamesForType(TestBean.class);
    String[] beansFromAppBeanFactory = configurableListableBeanFactory.getBeanNamesForType(TestBean.class);

    System.out.println(beansFromAppContext.length);
    System.out.println(beansFromBootstrapContext.length);
    System.out.println(beansFromAppBeanFactory.length);
  }

  @Configuration
  @EnableAutoConfiguration
  static class TestConfiguration {

  }
}

输出为:

0
1
0

问题是:

是否可以在Spring Boot Test中直接自动联结父-bootstrap应用程序上下文或属于它的ConfigurableListableBeanFactory?我想避免致电getParent

我也无法通过子应用程序上下文找到在bootstrap应用程序上下文中定义的bean,这似乎很奇怪-这是所需的行为吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...