一、Spring AOP的简单实例

[color=violet]1[/color]. 往pom.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



[color=violet]2[/color]. 在src/main/resources目录下新建spring-aop.xml文件:


  xmlns:aop="http://www.springframework.org/schema/aop"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"
  default-autowire="byName">

 
  
 
  
 
 
 
 

 




[color=violet]3[/color]. MyAspect切面类:

public class MyAspect {
public void beforeAdvice() {
System.out.println("beforeAdvice() is executed!");
}
}


[color=violet]4[/color]. Graceful目标类:

public class Graceful {
public void analogous() {
System.out.println("Analogous() is being executed");
}
}


[color=violet]5[/color]. BeforeAdviceTest测试类:

public class BeforeAdviceTest {
@Test
public void test() {
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans-aop.xml");
Graceful graceful = ctx.getBean("grace", Graceful.class);
graceful.analogous();
}
}


运行test()方法,输出:

beforeAdvice() is executed!
Analogous() is being executed


附:
①. 需要添加proxy-target-class="true"属性,防止使用JDK代理导致在获取实例并转换为Graceful时报错。

②. 不管是目标类还是切面类,都要交由spring托管,并委托CGLIB改写目标类。

你可能感兴趣的:(spring/ejb)