不讲概念,只看代码
1、配置类
@Configuration//配之类
@EnableAspectJAutoProxy//启用AspectJ自动代理
@ComponentScan(basePackages = {"spring01","spring02"}) //basePackages指定扫描的包
public class Config {
}
2、切面类
@Aspect
@Component
public class Audience {
/**
* 相当于访问相同报下的不同的类,他们拥有相同的包路径,可以定义一个变量
*/
@Pointcut("execution(* spring02.aspect.Performance.perform(..))")
public void performance(){
}
@Before("performance()")
public void silenceCellPhones(){
System.out.println("====表演前将手机调静音");
}
@Before("performance()")
public void takeSeats(){
System.out.println("====表演前就做");
}
@AfterReturning("performance()")
public void applause(){
System.out.println("====表演后鼓掌");
}
@AfterThrowing("performance()")
public void demandRefund(){
System.out.println("====表演失败时退款");
}
@Around("performance()")
public void watchPerformance(ProceedingJoinPoint point){
try {
System.out.println("====观看前1");
point.proceed();
System.out.println("====观看后2");
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
}
3、被通知对象接口
public interface Performance {
void perform();
}
4、被通知对象实现类
@Component("performance")
public class PerformanceImpl implements Performance{
@Override
public void perform() {
System.out.println("======表演开始=====");
}
}
5、测试类
@RunWith(SpringJUnit4ClassRunner.class)//启动测试时创建Spring上下文
@ContextConfiguration(classes = {Config.class})//配置文件对象
public class TestClass {
@Autowired
private Performance performance;
@Test
public void test(){
performance.perform();
}
}