1

我尝试实现 AOP,但(java.lang.ClassCastException) java.lang.ClassCastException: $Proxy0 cannot be cast to myPackage.Person在 (2) 行出现异常。可能是什么问题呢?Person必须是线程,所以它扩展了类Thread

主要的

1. ApplicationContext ctx = new ClassPathXmlApplicationContext("config/appContext.xml");
2. Person p = (Person)ctx.getBean("p1");
3. p.start(); 

public class Person extends Thread{

    private String name;

    public Person(String name) {
        setPersonName(name);
    }

    public void setPersonName(String name) {
        this.name = name;
    }    
}

方面

public class LogSettersCalls {

    public void logSetterCall(JoinPoint theJoinPoint)
    {
        String methodName = theJoinPoint.getSignature().getName();
        Object newValue = theJoinPoint.getArgs()[0];
        Object theObject = theJoinPoint.getTarget();
        System.out.println(theObject );
    }
}

配置

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"
       default-lazy-init="true">

    <aop:config>
        <aop:pointcut expression="execution(void set*(*))" id="theSettersLogger" />
        <aop:aspect ref="logSettersCallsBean">
            <aop:before pointcut-ref="theSettersLogger" method="logSetterCall"/>
        </aop:aspect>
    </aop:config>
   <bean id="logSettersCallsBean" class="aop.LogSettersCalls" />


    <bean id="p1" class="myPackage.Person" >    
        <constructor-arg index="0" type="java.lang.String" value="igor"/>
    </bean>
</beans>

df

4

1 回答 1

1

撇开我不确定它是否直观或是否适合派生(你不能使用组合或类似的东西吗?)这一事实不谈PersonThread我怀疑问题是 AOP 正在重写你的类,它不再是Person.

我会将实现 ( PersonImpl) 与合适的接口 ( Person) 分开,然后演员表应该可以工作。

于 2012-08-23T08:23:08.027 回答