How to inject an JDK Proxied class in Spring which

2019-07-14 07:52发布

I have a fairly odd set of circumstances. I'm using Spring 3.0.6 with a bean which implements and interface. So far, pretty normal stuff. My bean also has some protected methods. I'm using some AOP (JDK Proxies) and everything works fine.

My problem comes in when I want to inject this bean into another package class. Under normal circumstances, I would be able to inject the implementation and get access to the protected methods. Unfortunately, since it is JDK proxied, I can only inject based on the interface.

Since I need access to the protected methods, I cannot declare the methods in the interface, so I'm somewhat in a catch-22 situation. I tried switching to CGLIB proxies, but they crash with other advisors advising beans with final methods, etc) so that isn't really a solution.

Any suggestions as to what I can do? I've tried using a @PostConstruct method to retrieve the bean from the application context, but there too (not surprisingly) it is only able to retrieve the Proxied bean and consequently cannot cast it to the implementation required.

Any suggestions would be appreciated.

Thanks!

Eric

1条回答
做个烂人
2楼-- · 2019-07-14 08:48

The solution I can think of is to fetch implementation from proxy object.

http://www.techper.net/2009/06/05/how-to-acess-target-object-behind-a-spring-proxy/

As given in above link "((Advised)proxy).getTargetSource().getTarget()" returns target implementation fro proxy object. Now you can cast this target object into the Impl class & then on that impl class you can call protected method.

See if this works.

查看更多
登录 后发表回答