使用spring实现aop有四种方式:
1)基于代理的经典Spring AOP;
2)纯POJO切面;
3)@AspectJ注解驱动的切面;
4)注入式AspectJ切面;
这四种方式的实现,参考:实例讲解Java的Spring框架中的AOP实现
以3)方式为例子:
一.创建接口和实现类
Performance.java
package concert;
public interface Performance {
public void perform();
}
Mowenwei2016.java
package concert;
public class Mowenwei2016 implements Performance{
public void perform(){
System.out.println("DaGaHao, I'm MoWenWei !");
}
}
二.定义切面类
Audience.java
package concert;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class Audience {
@Pointcut("execution(** concert.Performance.perform(..))")
public void performance(){}
@Before("performance()")
public void silenceCellPhones(){
System.out.println("Silencing cell phones");
}
@AfterReturning("performance()")
public void applause(){
System.out.println("CLAP CLAP !!!");
}
@AfterThrowing("performance()")
public void demandRefund(){
System.out.println("Demanding a refund");
}
}
三.添加配置类
ConcertConfig.java
package concert;
import org.springframework.context.annotation.*;
@Configuration
@EnableAspectJAutoProxy
public class ConcertConfig {
@Bean
public Audience audience(){
return new Audience();
}
@Bean
public Performance Mowenwei2016(){
return new Mowenwei2016();
}
}
其中@EnableAspectJAutoProxy表示启用自动代理功能,这一步也可以替换成使用xml配置,在xml中使用<aop:aspectj-autoproxy/>
来启用AspectJ的自动代理;
四.测试
ConcertTest.java
package concert;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=ConcertConfig.class)
//@ContextConfiguration(locations = {"classpath:ConcertConfig.xml"})
public class ConcertTest {
@Autowired
private Performance cd;
@Test
public void cdShouldNotBeNull(){
assertNotNull(cd);
cd.perform();
}
}
测试结果:
Silencing cell phones
DaGaHao, I'm MoWenWei !
CLAP CLAP !!!
注意,依赖包:aspectjrt.jar、aspectjweaver.jar、aopalliance.jar、common-logging.jar;需要依赖aspectj的包是因为使用了aspectj的注解,aop的功能是spring自己实现的;