简体   繁体   English

Spring ApplicationContext.getBean(Class c)不适用于代理类

[英]Spring ApplicationContext.getBean(Class c) not working for proxy classes

I need to look up beans via their class type. 我需要通过类类型查找bean。 When the beans have been wrapped by a Proxy (some methods are @Transactional) - the ApplicatoinContext fails to find them. 当bean被代理包装时(某些方法是@Transactional) - ApplicatoinContext无法找到它们。 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. 我知道bean是我正在寻找的类型,但getBean()方法失败。

I can debug (and fix) the problem in Spring's AbstractBeanFactory code. 我可以调试(并修复)Spring的AbstractBeanFactory代码中的问题。 The issue is that it checks the type of the beanInstance against type I'm requesting but the beanInstance.getClass() is a Proxy. 问题是它根据我要请求的类型检查beanInstance的类型,但beanInstance.getClass()是一个代理。 AbstractBeanFactory should compensate for this and compare the type to the proxy's target class. AbstractBeanFactory应该对此进行补偿,并将类型与代理的目标类进行比较。

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? 我有一个修复此问题,但我不是特别想使用修补版本的Spring,我怀疑必须有一些我可以配置来使这个工作,或者这真的是一个错误?

There are two major ways Spring implements AOP (eg @Transactional support): either by using proxy interfaces or CGLIB. Spring实现AOP有两种主要方式(例如@Transactional支持):使用代理接口或CGLIB。

With interfaces (default) if your class implements any interfaces, Spring will create a proxy implementing all that interfaces. 使用接口(默认)如果您的类实现任何接口,Spring将创建一个实现所有接口的代理。 From now on you can only work with your bean through that interfaces. 从现在开始,您只能通过该接口使用您的bean。 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. Spring将创建一个子类(obvoiusly仍然实现所有接口)。 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. 不,当然这不是一个bug,而是众所周知的行为,不,没有必要修补Spring。

See also 也可以看看

<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. 在applicationContext.xml中写下这三行,这对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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