欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

$Proxy0 cannot be cast to com.performer.service.impl.PoeticJuggler 博客分类: Spring $Proxy0 cannot be cast toaop异常 

程序员文章站 2024-03-15 13:10:29
...

在测试Spring Aop时遇到如下异常:

Exception in thread "main" java.lang.ClassCastException: $Proxy0 cannot be cast to com.performer.service.impl.PoeticJuggler

 

代码如下所示:

package com.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.performer.service.Performer;
import com.performer.service.impl.Instrumentalist;
import com.performer.service.impl.PoeticJuggler;

public class SpringTest {
	public static void main(String []args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("spring12.xml");
		
		PoeticJuggler p0 = (PoeticJuggler) context.getBean("duke");
		p0.perform();
		
		Instrumentalist p1 = (Instrumentalist) context.getBean("jake");
		p1.perform();
	}
}

 

解决办法:将p0和p1前面的类换成Performer,即接口的名字。

Performer p0 =   (Performer) context.getBean("duke");
p0.perform();
		
Performer p1 =   (Performer) context.getBean("jake");
p1.perform();

 

经验证,异常消失。

 

参考文章:

http://mopishv0.blog.163.com/blog/static/54455932200911118572079/