Spring Aop开发测试
前菜
代理模式
首先温习下代理模式,然后看下代理模式的接口设计
代理类实现目标委托类的接口,然后构造方法注入委托类;
代码:在SpringStudy\src\main\java\com\aop\base\common下
修饰者模式
在运行时加强
跟代理模式类似,但是有一个修饰链,可以根据修饰链,进行增强
因为跟aop不相关,暂时不介绍
aop简单入门demo流程
关于aop的一些概念,网上都有,链接给你们:
https://www.cnblogs.com/liuruowang/p/5711563.html
我这里介绍的demo是基于spring的javaConfig的简单Demo
1.创建目标对象接口
2.创建实现类,作为Bean
3.配置SpringConfig类
4.定义切面类
5.测试类(偷懒,将测试类放入PerformanceTest中的@Test方法中了)
代码如下:
public interface Performance {
public void performance();
}
@Component
public class PerformanceTest implements Performance {
@Override
public void performance() {
System.out.println("开始进行性能测试");
List list=new ArrayList();
list.get(2);
}
@Test
public void test(){
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
Performance bean = context.getBean(Performance.class);
bean.performance();
}
}
@Configuration
@ComponentScan("com.aop.java")
@EnableAspectJAutoProxy
public class SpringConfig {
}
@Component("test")
@Aspect
public class Audience {
@Before("execution(* com.aop.java.Performance..*(..))")
public void silenceCcellPhone(){
System.out.println("Sliening cell phone");
};
@Before("execution(* com.aop.java.Performance..*(..))")
public void takeSeats(){
System.out.println("Tasking seats");
};
@AfterReturning("execution(* com.aop.java.Performance..*(..))")
public void applause(){
System.out.println("CLAP CLAP ");
};
@AfterThrowing("execution(* com.aop.java.Performance..*(..))")
public void demandRefund(){
System.out.println("Demanding a refund");
};
}
@Test
public void test(){
//加载配置类
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
//获取bean
Performance bean = context.getBean(Performance.class);
//执行bean方法
bean.performance();
}