ClassCastException $ Proxy无法使用aop强制转换为

我正在使用spring通过bean创建对象。 现在我尝试使用aop创建相同的对象,我得到$ Proxy无法转换为SaleRoomexception。

以前的xml是:

       

我使用以下代码创建销售:

  ApplicationContext context = new FileSystemXmlApplicationContext(SalesManager.getSalesSourceFile()); SaleRoom saleRoom; List salesNames = new LinkedList(); List allSales = new LinkedList(); // Get all sales id's for beans NodeList salesNodeList = salesDoc.getElementsByTagName("bean"); for (int i = 0; i < salesNodeList.getLength(); i++) { Node nNode = salesNodeList.item(i); salesNames.add(((Element) nNode).getAttribute("id").toString()); } for (String saleName : salesNames) { if(saleName.contains("sale")) { saleRoom = (SaleRoom) context.getBean(saleName); allSales.add(saleRoom); } } return allSales; 

这是新的xml:

            

Aspect日志记录类:

 @Aspect public class LogSettersCalls { @Pointcut("execution(void set*(*))") public void setMethod() {} @Before("setMethod()") public void logSetterCall(JoinPoint theJoinPoint) { String methodName = theJoinPoint.getSignature().getName(); Object newValue = theJoinPoint.getArgs()[0]; Object theObject = theJoinPoint.getTarget(); System.out.println("The method " + methodName + " is called on object " + theObject + " with the value " + newValue); } } 

我使用相同的代码通过aop创建bean。 我在线程“main”java.lang.ClassCastException中得到Exception:$ Proxy11无法强制转换为application.common.entities.SaleRoom

抛出exception的行:saleRoom =(SaleRoom)context.getBean(saleName);

任何帮助将不胜感激。 谢谢。

您的SaleRoom类是否实现了某些界面? 如果是,那么你应该在代码中使用接口而不是类:

 ISaleRoom saleRoom = (ISaleRoom) context.getBean(saleName); 

因为如果你的bean实现了一些接口,那么Spring默认会根据这个接口创建代理。

这是一篇关于Spring中代理创建的好文章。

如果要为目标类创建代理,也可以更改Spring AOP的代理机制。 这在参考文档中进行了描述。