Spring源码分析-AOP
动态 AOP 使用示例
创建用于拦截的 bean
1
2
3
4
5
6
7
8
public class TestBean {
private String testStr = "test";
public void test() {
System.out.println("test");
}
}创建 Advisor
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class AspectJTest {
public void test() {
}
public void beforeTest() {
System.out.println("beforeTest");
}
public void afterTest() {
System.out.println("afterTest");
}
public Object aroundTest(ProceedingJoinPoint p) {
System.out.println("brfore around");
Object o = null;
try {
o = p.proceed();
} catch (Throwable e) {
e.printStackTrace();
}
System.out.println("after around");
return o;
}
}创建配置文件
1
2
3<aop:aspectj-autoproxy />
<bean id="testBean" class="io.github.binglau.bean.TestBean" />
<bean class="io.github.binglau.AspectJTest" />测试
1
2
3
4
5
6
public void testAop() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beanFactory.xml");
TestBean bean = (TestBean) ctx.getBean("testBean");
bean.test();
}不出意外结果
1
2
3
4
5brfore around
beforeTest
test
after around
afterTest
可知 <aop:aspectj-autoproxy />
是开启 aop 的关键,我们不妨由此入手。