Proxy cannot be cast to CLASS

后端 未结 2 1829
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-01 17:51

I\'m using Spring for wiring dependencies specifically for DAO classes that use Hibernate, but I\'m getting an exception that has me puzzled:

$Proxy58 cannot be

相关标签:
2条回答
  • 2021-02-01 18:12

    Spring uses JDK dynamic proxies by default ($Proxy58 is one of them), that can only proxy interfaces. This means that the dynamically created type $Proxy58 will implement one or more of the interfaces implemented by the wrapped/target class (UserDao), but it won't be an actual subclass of it. That's basically why you can cast the userDao bean to the Dao interface, but not to the UserDao class.

    You can use <tx:annotation-driven proxy-target-class="true"/> to instruct Spring to use CGLIB proxies that are actual subclasses of the proxied class, but I think it's better practice to program against interfaces. If you need to access some methods from the proxied class which are not declared in one of it's interfaces, you should ask yourself first, why this is the case?
    (Also, in your code above there are no new methods introduced in UserDao, so there is no point in casting the bean to this concrete implementation type anyway.)

    See more about different proxying mechanisms in the official Spring reference.

    0 讨论(0)
  • 2021-02-01 18:19

    I was writing unit tests and needed to be able to stub out the DAOs for some calls. Per This guys post: http://www.techper.net/2009/06/05/how-to-acess-target-object-behind-a-spring-proxy/ I used his method provided:

    @SuppressWarnings({"unchecked"})
    protected <T> T getTargetObject(Object proxy, Class<T> targetClass) throws Exception {
      if (AopUtils.isJdkDynamicProxy(proxy)) {
        return (T) ((Advised)proxy).getTargetSource().getTarget();
      } else {
        return (T) proxy; // expected to be cglib proxy then, which is simply a specialized class
      }
    }
    

    Then you can easily call it with the proxy and get the object behind the proxy and manipulate the objects in it directly as needed.

    0 讨论(0)
提交回复
热议问题