一、Spring AOP的简单实例
[color=violet]1[/color]. 往pom.xml文件添加以下依赖: [code="xml"] org.testng testng 6.4 test org.springframework spring-context 3.1.2.RELEASE cglib cglib 2.2.2 org.aspectj aspectjweaver 1.7.0 [/code] [color=violet]2[/color]. 在src/main/resources目录下新建spring-aop.xml文件: [code="xml"] [/code] [color=violet]3[/color]. MyAspect切面类: [code="java"] public class MyAspect { public void beforeAdvice() { System.out.println("beforeAdvice() is executed!"); } } [/code] [color=violet]4[/color]. Graceful目标类: [code="java"] public class Graceful { public void analogous() { System.out.println("Analogous() is being executed"); } } [/code] [color=violet]5[/color]. BeforeAdviceTest测试类: [code="java"] public class BeforeAdviceTest { @Test public void test() { AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans-aop.xml"); Graceful graceful = ctx.getBean("grace", Graceful.class); graceful.analogous(); } } [/code] 运行test()方法,输出: beforeAdvice() is executed! Analogous() is being executed 附: ①. 需要添加proxy-target-class="true"属性,防止使用JDK代理导致在获取实例并转换为Graceful时报错。 ②. 不管是目标类还是切面类,都要交由spring托管,并委托CGLIB改写目标类。