首先,上测试结构
搭建工具:Maven quickstart模板。
环境:Spring-context、Spring-aspects、Junit
其中,MyAspect是通过aspectj注解创建的代理类。StudentService为Student的实现类。MyAspect对于StudentService中的doSome方法进行增强。
错误代码
众所周知,Spring可以通过动态代理的方式为对目标类进行拦截或者增强。而在ApplicationContext对象在获取对象时,需要进行一步强制转换。于是,代码示例如下:
@Test
public void shouldAnswerWithTrue()
{
String config="applicationContext.xml";
ApplicationContext ac=new ClassPathXmlApplicationContext(config);
StudentService ss=(StudentService) ac.getBean("MyStudent");
ss.doStudent();
}
发现程序报错:
java.lang.ClassCastException: class jdk.proxy2.$Proxy8 cannot be cast to class org.example.domain.StudentService (jdk.proxy2.$Proxy8 is in module jdk.proxy2 of loader 'app'; org.example.domain.StudentService is in unnamed module of loader 'app')
at org.example.AppTest.shouldAnswerWithTrue(AppTest.java:26)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)
信息很明确:类型强转失败!(java.lang.ClassCastException)
为什么会这样呢?
分析
事实上,Proxy(动态代理实现类之一)所创建的实例对象,继承了与StudentService同样的接口,也就是Student,他是通过反射创建了一个融合了StudentService的doStudent方法与MyProxy切面类中的修饰方法的一个动态类,同样继承Student接口,但与StudentService无关。显然,无法进行强制类型转换。
代码修改测试
@Test
public void shouldAnswerWithTrue()
{
String config="applicationContext.xml";
ApplicationContext ac=new ClassPathXmlApplicationContext(config);
Student ss=(Student) ac.getBean("MyStudent");
ss.doStudent();
}
运行之,单元测试通过