Spring ApplicationContext.getBean (class c) does not work for proxy classes

I need to look for beans through their class type. When beans were wrapped by proxies (some methods are @Transactional) - ApplicatoinContext does not find them. I find that if I look through them through an interface, it works, but in this case I work with a specific class type. I know that a bean is of the type I'm looking for, but the getBean () method fails.

I can debug (and fix) the problem in Spring AbstractBeanFactory code. The problem is that it checks the beanInstance type for type I, but beanInstance.getClass () is a proxy server. AbstractBeanFactory should compensate for this and compare the type with the target proxy class.

I have a fix for this, but I really don't want to use a fixed version of Spring, and I suspect there must be something that I can tweak to get this to work, or is it really a bug?

+6
source share
2 answers

There are two main ways: Spring implements AOP (for example, @Transactional support): either using proxy interfaces, or with CGLIB.

With interfaces (default), if your class implements any interfaces, Spring will create a proxy server that implements all these interfaces. From now on, you can only work with your bean interface. Your class is deeply immersed in them.

If you enable proxying of target classes instead of :

 <aop:config proxy-target-class="true"> 

Spring will create a subclass (obvoiusly still implementing all your interfaces). This will fix your problem. However, remember that the returned object is not your class, but a dynamically created subclass that wraps and delegates your original object. This should not be a problem in most cases.

And no, of course, this is not a mistake, but well-known behavior and no, there is no need to fix Spring.

see also

+11
source
 <context:component-scan base-package="<Your base package name goes here>" /> <aop:aspectj-autoproxy /> <aop:config proxy-target-class="true"/> 

write these three lines in applicationContext.xml, it worked for me.

+1
source

Source: https://habr.com/ru/post/920774/


All Articles