简体   繁体   中英

How to check the type of request scoped bean in Spring?

I am trying to write a Junit test that would make sure that the Configuration classes of my other tests are set up correctly. During this test I would like to check if the beans which are set up are real implementations or dummy implementations. I have run into a problem however with trying to verify the type of request scoped beans.

When I set up the beans like this:

@Bean
public MyBeanAI myBeanAI() {
    return new MyBeanA();
}

@Bean
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public MyBeanBI myBeanBI() {
    return new MyBeanB();
}

In the test code:

Assert.assertTrue(myBeanAI instanceof MyBeanA);  // Succeeds
Assert.assertTrue(myBeanBI instanceof MyBeanB);  // Fails

What is the best way to check the implementation type of a request scoped bean? I have tried .isAssignableFrom() but it produces the same result. The only way I see right now is to use myBeanB.toString() and if it is not overridden in my class, the proxy will print out the name of the base type. bean.getClass() however returns com.sun.proxy.$Proxy44

There is a similar question on SO ( Obtain real Class object for Spring bean ) which also wants to obtain information about the class behind the Proxy, but the question and answers deal only with the class object which is used as the return type of the bean definition. In my case I do not need information about the interface which was used to create the bean but rather the actual implementation behind it. Fortunately the same API pointed out at that question offers another method which suits for my needs.

I will add an answer myself. Thanks to David Lavender for pointing out the other question in the comments

As pointed out by David Lavender in the comments there is a similar question which deals with obtaining the Class behind the proxy at ( Obtain real Class object for Spring bean ). Using other methods of the Advised and TargetSource interfaces, it was also possible to obtain the exact implementation behind the proxy:

Assert.assertTrue(((Advised) myBeanBI).getTargetSource().getTarget() instanceof MyBeanB);

Please note that the methods used in the other question allow to obtain the interface behind the proxied bean.

Assert.assertTrue(((Advised) myBeanBI).getTargetSource().getTargetClass().equals(MyBeanBI.class));

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