使用AspectJ的SpringAOP简介 [英] SpringAOP introductions with AspectJ
问题描述
我是SpringAOP的新手.我想写一个简单的简介示例,但不清楚它必须如何工作.
I'm new in SpringAOP. I want to write simple example of Introductions but can't understand clearly how it must work.
在文档中,我发现:
我写一个简单的例子: 我用一种方法编写简单的类
And I write simple example: I write simple class with one method
public class Test {
public void test1(){
System.out.println("Test1");
}
}
然后我编写接口和实现该接口的类
Then I write interface and class that implements this 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配置文件如下所示:
my spring configuration file look like this:
<aop:aspectj-autoproxy/>
<bean id="aspect" class="by.bulgak.aspect.AspectClass" />
所以我的问题是: 我现在怎么能这样.我需要在我的主要班级上写些什么以取得优异成绩? 可能需要编写其他一些类.(我在其中读到有关SpringAOP的书,但找不到完整的示例)
So my question: How can I you this now. what I need to write in my main class to sea result? May be I need to write some other classes.(book in which I read about SpringAOP I can't find full examples)
更新
我的主要方法如下:
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();
}
当我执行我的应用程序时,出现此错误:
When I execute my app i get this error:
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
:
First you need to define the bean Test
in your configuration file:
<bean id="test" class="Test" />
然后在主目录中,从ApplicationContext
获取此bean:
Then in main, get this bean from ApplicationContext
:
Test test1 = (Test) context.getBean("test");
现在,从test1
参考中,您只能调用在Test
bean中定义的方法.要使用新引入的行为,您需要将引用类型转换为包含该行为的接口:
Now, from test1
reference, you can only invoke method defined in Test
bean. To use the newly introduced behaviour, you need to typecast the reference to the interface containing that behaviour:
ITest2 test2 = (ITest2) context.getBean("test");
然后,您可以从此参考文献中访问Test2
的方法:
Then, you can access the method of Test2
from this reference:
test2.test2();
这将调用@DeclareParents
批注的defaultImpl
属性中指定的Bean中定义的方法.
This will invoke the method defined in the bean as specified in the defaultImpl
attribute of @DeclareParents
annotation.
这篇关于使用AspectJ的SpringAOP简介的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!