spring 切面织入报错:java.lang.ClassCastException: com.sun.proxy.$Proxy7 cannot be cast to...

报这个错,只有一个原因,就是转化的类型不对.

接口过父类的子类,在强制转换的时候,一定要用接口父类来定义。

代码示例:

package com.luoluo.dao.impl;

import java.sql.Connection;
import java.sql.SQLException;

import javax.annotation.Resource;
import javax.sql.DataSource;

import com.luoluo.dao.UserDAO;
import com.luoluo.model.User;

public class UserDAOImpl implements UserDAO {
	private DataSource dataSource;
	

	public DataSource getDataSource() {
		return dataSource;
	}

	@Resource
	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}
	
	public void save(User user) {
		//Hibernate
		//JDBC
		//XML
		//NetWork
		try {
			Connection conn = dataSource.getConnection();
			conn.createStatement().executeUpdate("insert into user values (null,‘zhang‘,‘123456‘)");
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("user saved!");
	}

	@Override
	public void delete(User user) {
		System.out.println("user deleted!");		
	}

}

 

package com.luoluo.myapp;

import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.luoluo.dao.UserDAO;
import com.luoluo.dao.impl.LogInterceptor;
import com.luoluo.model.User;

public class UserServiceTest {
	@Test
	public void testAspect(){
		ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(new String[] {"servlet-context.xml", "root-context.xml"});
		UserDAO userDAOImpl=(UserDAO)ctx.getBean("userDAOImpl");//由于UserDAOImpl实现了UserDAO接口,所以强制转换必须用父类UserDAO来定义
		
		LogInterceptor logInterceptor =(LogInterceptor) ctx.getBean("logInterceptor");
		System.out.println(logInterceptor.getClass().getName());
		userDAOImpl.save(new User());
		userDAOImpl.delete(new User());
	}

}

  

  

 

spring 切面织入报错:java.lang.ClassCastException: com.sun.proxy.$Proxy7 cannot be cast to...,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。