Spring ApplicationContext.getBean(Class c) not wor

2019-03-29 11:48发布

问题:

I need to look up beans via their class type. When the beans have been wrapped by a Proxy (some methods are @Transactional) - the ApplicatoinContext fails to find them. I find that if I look them up via an interface, it works but in this case I'm working with a concrete class type. I know the bean is of the type I'm looking for but the getBean() method fails.

I can debug (and fix) the problem in Spring's AbstractBeanFactory code. The issue is that it checks the type of the beanInstance against type I'm requesting but the beanInstance.getClass() is a Proxy. AbstractBeanFactory should compensate for this and compare the type to the proxy's target class.

I have a fix for this but I don't particularly want to use a patched version of Spring and I suspect there must be something I can configure to get this working, or is this really a bug?

回答1:

There are two major ways Spring implements AOP (e.g. @Transactional support): either by using proxy interfaces or CGLIB.

With interfaces (default) if your class implements any interfaces, Spring will create a proxy implementing all that interfaces. From now on you can only work with your bean through that interfaces. Your class is deeply burried inside them.

If you enable proxying target classes instead via cglib:

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

Spring will create a subclass (obvoiusly still implementing all your interfaces) instead. This will fix your problem. However remember that the returned object is not really your class but dynamically generated subclass that wraps and delegates to your original object. This shouldn't be a problem in most of the cases.

And no, of course this is not a bug but well known behaviour and no, there is no need to patch Spring.

See also

  • Location of the proxy class generated by Spring AOP
  • Getting Spring Error "Bean named 'x' must be of type [y], but was actually of type [$Proxy]" in Jenkins
  • How to mix CGLIB and JDK proxies in Spring configuration files?
  • Mocking a property of a CGLIB proxied service not working


回答2:

<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 this worked for me.