1. 程式人生 > >hibernate-spring測試報錯:com.sun.proxy.$Proxy44 cannot be cast to com.mm.service.imp.RoleServic

hibernate-spring測試報錯:com.sun.proxy.$Proxy44 cannot be cast to com.mm.service.imp.RoleServic

錯誤內容

java.lang.ClassCastException: com.sun.proxy.$Proxy44 cannot be cast to com.mm.service.imp.RoleServiceImp


測試程式碼

ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
		RoleServiceImp bean = (RoleServiceImp) context.getBean("roleService");
		Role r = new Role();
		r.setName("超級管理員");
		bean.save(r);

其中繼承關係,以及注入為:

@Service(value="roleService")
public class RoleServiceImp implements RoleService {...}

錯誤原因:通過context.getBean(“xxx”)獲取到的物件要轉為父介面型別


將程式碼改成如下即可:

ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
		RoleService bean = (RoleService) context.getBean("roleService");