测试 Spring aop时出现java.lang.ClassCastException的错误

代码如下:

public class UserTest {
    
    private static UserServiceImpl userService ;
    
    @BeforeClass
    public static void iniUserService(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml") ;
        userService = (UserServiceImpl) applicationContext.getBean("userService") ;
    }
    
    @Test
    public void test() {
        User user = new User(3,"shpengfish@gmail.com","ysp","123456","yushipeng",new Date()) ;
        System.out.println(user);
        userService.saveEntity(user) ;
    }

}

 

  junit 报错 

java.lang.ClassCastException: com.sun.proxy.$Proxy13 cannot be cast to com.ysp.surveypark.service.impl.UserServiceImpl
  后来上网搜索了下该问题,是因为 UserServiceImpl 实现了 UserService 接口,而该测试类中 却是使用 UserServiceImpl 声明的,这并没有体现出面向接口编程的思想,而 aop 使用的JDK 代理是基于接口的,因此报错,将实现类改为接口类型即可。 

 

posted @ 2015-01-15 13:02  苏陌Bubble  阅读(1708)  评论(0编辑  收藏  举报