作为AOP入门基础的学习材料,大家可以参考这个。
@AspectJ Based AOP with Spring
我自己是参考《Spring实战》的。
不废话,先贴上代码:
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.10</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.10</version>
</dependency>
接下来是切面(切点+通知)
package com.banana.oa.aop;
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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Aspect
public class Audience {
private static Logger logger = LoggerFactory.getLogger(Audience.class);
@Pointcut("execution(* com.banana.oa.aop.Performance.perform(..))")
public void performance() {}
@Before("performance()")
public void silenceCellPhone() {
logger.info("silence cell phone");
}
@Before("performance()")
public void takeSeats() {
logger.info("take seats");
}
@AfterReturning("performance()")
public void applause() {
logger.info("CLAP CLAP CLAP");
}
@AfterThrowing("performance()")
public void demandRefund() {
logger.info("Demanding a refund");
}
}
切点的具体类:
package com.banana.oa.aop;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Performance {
private static final Logger logger = LoggerFactory.getLogger(Performance.class);
public void perform() {
logger.info("perform ...");
}
}
Bean配置,我自己比较喜欢使用Java配置,而且类型也跟安全。需要注意的是要加上@EnableAspectJAutoProxy
注解。
package com.banana.oa.spring;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import com.banana.oa.aop.Audience;
import com.banana.oa.aop.Performance;
@Configuration
@EnableAspectJAutoProxy
public class AopConfig {
@Bean
public Audience audience() {
return new Audience();
}
@Bean
public Performance performance() {
return new Performance();
}
}
Unit Test类,需要注意的是,这里的Performance需要通过注入的方式装配进来,自己new的对象会达不到AOP效果。
package com.banana.oa.service;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.banana.oa.aop.Performance;
public class PerformanceTest extends BaseTest {
/*
* AOP test
* must be provided in inject way, otherwise AOP won't work if we new a Performance object
*/
@Autowired
private Performance performance;
@Test
public void testPerform() {
performance.perform();
}
}