简体   繁体   中英

How to spy on bootstrap context beans

I am using spring.factories to set bootstrap context

org.springframework.cloud.bootstrap.BootstrapConfiguration=sompePackage.MyBootstrapConfiguration

I was following what is mentioned in this link https://cloud.spring.io/spring-cloud-commons/multi/multi__spring_cloud_context_application_context_services.html

I noticed 2 things hope you please can help me with

1- I cannot spy on any bean that is created through the bootstrap context, in other words, if I create a bean of type x in MyBootstrapConfiguration, spying on that bean with @SpyBean is not working, I can spy on all other beans but the bootstrap context ones (I am using springboottest)

2- If I inject ApplicationContext somewhere and print all the defined beans, i cannot see the beans that were created in the bootstrap context, in other words, the bean x that is created in MyBootstrapConfig is not there. However, @Autowired is working fine and the bean is injected correctly.

My questions are: 1- How can i spy or mock the bootstrap context beans? 2- If i cannot find these beans in ApplicationContext, where are they?

Thanks,

尝试将断点放在创建bean的位置并以调试模式运行,然后您将发现是否已创建bean

You could define your own context for the test scope you are trying to run:

This would look something like:

public class TestApplicationContext implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(final ApplicationContext context) throws 
  BeansException {
    TestApplicationContext.context = context;
}

public static Object getBean(final String beanName) {
    return context.getBean(beanName);
   }
}

Then you can create a bean for the context in a @Configuration annotated class.

@Bean
public TestApplicationContext testApplicationContext() {
    return new TestApplicationContext();
}

Then you can easily reference whatever bean you need by simply:

 TestApplicationContext.getBean("someBean");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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