Spring AOP, declare-parents cast exception

2019-09-11 06:43发布

I have:

  • an interface GenericDao
  • a class GenericDaoImpl implements GenericDao
  • a class UserDao

What I want to do is:

UserDao userDao;
public void setUserDao(UserDao val) { userDao = val; }
...
((GenericDao) userDao).update(user);

My Beans.xml looks like:

<bean id="genericUserDao" class="dao.GenericDaoImpl">
  ...
  <property name="sessionFactory" ref="hibernateSessionFactory" />
</bean>

<bean id="userDao" class="dao.user.UserDao">
  <property name="sessionFactory" ref="hibernateSessionFactory" />
</bean>

<aop:config>
  <aop:aspect>
    <aop:declare-parents
            types-matching="dao.user.UserDao"
            implement-interface="dao.GenericDao"
            default-impl="genericUserDao" />
  </aop:aspect>
</aop:config>

And this is causing

java.lang.ClassCastException: dao.user.UserDao cannot be cast to dao.GenericDao

I also tried setting default-impl to: dao.user.UserDao but result is the same.

I couldn't find any good documentation or examples showing proper xml configuration.

What is wrong with my XML?

EDIT:

Here is full error stack:

Exception in thread "Thread-3" java.lang.ClassCastException: dao.user.UserDao cannot be cast to dao.GenericDao
    at dao.GenericDao$$FastClassBySpringCGLIB$$d43da5ef.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:133)
    at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:121)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
    at dao.user.UserDao$$EnhancerBySpringCGLIB$$957148da.update(<generated>)

1条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-09-11 07:16

I have found the solution.

  <aop:config>
    <aop:aspect>
      <aop:declare-parents
              types-matching="dao.user.UserDao+"
              implement-interface="dao.GenericDao"
              delegate-ref="genericUserDao" />
    </aop:aspect>
  </aop:config>

Needed to add plus sign (+) to types-matching and change default-impl to delegate-ref.

查看更多
登录 后发表回答