切点:
execution ( * cn.com.susq.concert.Performance.perform (..) )
execution : 方法执行时触发
* : 返回任意类型
cn.com.susq.concert.Performance.perform() 全限定类路径的方法名
(..) : 表示参数任意
demo:
定义需要被通知的方法
SpringAop在应用运行期织入切面,AOP容器会为目标对象动态的创建一个代理对象。因此,Spring对AOP的支持仅限于方法拦截。
package cn.com.susq.concert;
public interface Performance {
public void perform();
}
实现接口
import org.springframework.stereotype.Component;
/**
* Created by susq on 2017-8-27.
*/
public class PerformanceImpl implements Performance {
public void perform() {
System.out.println("被通知的方法执行");
}
}
定义切面
package cn.com.susq.concert;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
/**
* Created by susq on 2017-8-27.
*/
@Aspect
public class Audience {
@Pointcut("execution(* cn.com.susq.concert.Performance.perform(..))")
public void performance() {}
@Before("performance()")
public void silenceCellPhones() {
System.out.println("Silencing cellPhones");
}
//@After, @AfterReturning, @AfterThrowing 类似
@Around("performance()")
public void watchPerformance(ProceedingJoinPoint jp) {
try {
System.out.println("Silencing cell phones");
System.out.println("Taking seat");
jp.proceed();
System.out.println("Clap");
} catch (Throwable e) {
System.out.println("Demanding a refund");
}
}
}
aspectj.xml 配置启用AspectJ 自动代理
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">
<aop:aspectj-autoproxy /> <!-- 启用AspectJ 自动代理 -->
<bean id="audience" class="cn.com.susq.concert.Audience"/>
<bean id="performance" class="cn.com.susq.concert.PerformanceImpl"/>
</beans>
单元测试类
package cn.com.susq.concert;
import org.junit.Test;
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;
/**
* Created by susq on 2017-8-27.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:aspectj.xml")
public class AudienceTest {
@Autowired
private Performance performance;
@Test
public void testPerformance() {
performance.perform();
}
}
控制台输出
Silencing cell phones
Taking seat
Silencing cellPhones
被通知的方法执行
Clap