tags:

views:

396

answers:

2
+2  Q: 

Spring-AOP

i have configured a Spring-AOP on a bean. When i access this bean it returns me a spring proxy class instead of the actual bean. Is there any way i can get the actual bean.

ApplicationContext.xml

bean id = "abc" class = "abc.java"

some.java

abc a = (abc)applicationContext.getBean("abc")

this throws: java.lang.ClassCastException: $Proxy19

+1  A: 

You're going to have to cast it to a Proxy Object for starters for sure. Then try:

Proxy.getTargetSource().getTarget

I don't really have any idea if that will work, the AOP documentation is very ambiguous when describing return types for Proxy classes, it says stuff like "Returns

Gandalf
Thanx man your solution is partially correct. org.springframework.aop.framework.Advised class does the trick.Advised advised = (Advised) proxy;Target target = proxy.getTargetSource().getTarget();
hakish
Good to know. Glad to help.
Gandalf
This isn't an approach that the Spring guys would advocate, however, since it's invasive. Correctly configured AOP proxies are transparent to the application. If they're not, then it ain't really AOP.
skaffman
I think on of his issues may be the fact in AOP you can Proxy classes that don't implement any interface. So AOP kind of breaks the Proxy rules right from the start.
Gandalf
A: 

Depending on the class hierarchy of the target bean, Spring will generate either a proxy which extends the target bean's class (suing CGLIB), or it will generate a proxy which onl implements the target bean's interfaces.

If your target bean implements any interfaces, then the latter option will be selected. This is generally preferable. I'm guessing that your target class does indeed implement at least one interface. Could your code which obtains the bean cast the reference to the interface type instead of the class?

You can, however, force Spring AOP to generate proxies which extend the target bean's class, using the proxy-target-class option. The exact syntax depends on how you're configured the AOP, and you don't specify this in your question.

skaffman
i could solve my trouble using the org.springframework.aop.framework.Advised class.This enabled me to access the target class which is the actual bean itself.Thanks for ur inputs.
hakish