我是 SpringAOP 的新手。我想写一个简单的 Introductions 示例,但不能清楚地理解它是如何工作的。
在文档中我发现:
我写了一个简单的例子: 我用一种方法编写简单的类
public class Test {
public void test1(){
System.out.println("Test1");
}
}
然后我写接口(interface)和实现这个接口(interface)的类
public interface ITest2 {
void test2();
}
public class Test2Impl implements ITest2{
@Override
public void test2() {
System.out.println("Test2");
}
}
最后是我的一面
@Aspect
public class AspectClass {
@DeclareParents(
value = "by.bulgak.test.Test+",
defaultImpl = Test2Impl.class
)
public static ITest2 test2;
}
我的 spring 配置文件如下所示:
<aop:aspectj-autoproxy/>
<bean id="aspect" class="by.bulgak.aspect.AspectClass" />
所以我的问题是: 我怎么能这样呢。我需要在我的主课上写什么才能取得成功? 可能是我需要写一些其他的类。(我在其中阅读有关 SpringAOP 的书我找不到完整的例子)
更新
我的主要方法是这样的:
public static void main(String[] args) {
ApplicationContext appContext = new ClassPathXmlApplicationContext("spring-configuration.xml");
Test test = (Test) appContext.getBean("test");
test.test1();
ITest2 test2 = (ITest2) appContext.getBean("test");
test2.test2();
}
当我执行我的应用程序时,出现此错误:
Exception in thread "main" java.lang.ClassCastException: com.sun.proxy.$Proxy5 cannot be cast to by.bulgak.test.Test
在这一行:
Test test = (Test) appContext.getBean("test");
最佳答案
首先,您需要在配置文件中定义 bean Test
:
<bean id="test" class="Test" />
然后在 main 中,从 ApplicationContext
获取这个 bean:
Test test1 = (Test) context.getBean("test");
现在,从test1
引用,您只能调用定义在Test
bean 中的方法。要使用新引入的行为,您需要对包含该行为的接口(interface)的引用进行类型转换:
ITest2 test2 = (ITest2) context.getBean("test");
然后,您可以从这个引用中访问Test2
的方法:
test2.test2();
这将调用在 @DeclareParents
注释的 defaultImpl
属性中指定的 bean 中定义的方法。
关于java - SpringAOP 与 AspectJ 的介绍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17176169/