Spring ApplicationContext.getBean(Class c) not wor

2019-03-29 11:39发布

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?

2条回答
老娘就宠你
2楼-- · 2019-03-29 12:04
<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.

查看更多
再贱就再见
3楼-- · 2019-03-29 12:09

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 :

<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

查看更多
登录 后发表回答