Spring Aop动态代理
AOP:面向切面编程,在不影响核心代码的前提下,可以在任意位置添加非核心代码
使用spring的aop完成动态代理实现核心业务和非核心业务的一种抽取
步骤:
1.在pom.xml配置中引入依赖
<dependencies>
<!--spring-webmvc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<!--spring-jdbc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<!--面向切面-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
</dependencies>
2.在resource目录下创建配置文件(这里我叫application.xml)
<!--开启包扫描-->
<context:component-scan base-package="com"/>
3.创建一个接口和实现接口类
public interface ArithmeticCalculator {
/**
* 加法运算
* @param a
* @param b
* @return
*/
int add(int a ,int b);
/**
* 减法运算
* @param a
* @param b
* @return
*/
int sub(int a ,int b);
/**
* 乘加法运算
* @param a
* @param b
* @return
*/
int mul(int a ,int b);
/**
* 除加法运算
* @param a
* @param b
* @return
*/
int div(int a ,int b);
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~实现类~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@Component
public class ArithmeticCalculatorImpl implements ArithmeticCalculator{
@Override
public int add(int a, int b) {
int c=a+b;
return c;
}
@Override
public int sub(int a, int b) {
int c=a-b;
return c;
}
@Override
public int mul(int a, int b) {
int c=a*b;
return c;
}
@Override
public int div(int a, int b) {
int c=a/b;
return c;
}
}
4.创建一个切面类
@Component
@Aspect//表示该类为切面类
public class LogAspects {
//*:返回类型 包下的 类.方法.(参数)
@Before(value = "execution(* com.ganin.aop.after.*.*(..))") //service
public void before(JoinPoint joinPoint){ //Joinpoint 封装了SpringAop中切面方法的信息
String name = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
System.out.println("The "+name+" method begin with"+ Arrays.asList(args));
}
@After(value = "execution(* com.ganin.aop.after.*.*(..))") //后置通知finally
public void after(){
System.out.println("方法总是执行");
}
@AfterReturning(value = "execution(* com.ganin.aop.after.*.*(..))",returning = "returnValue")//后置返回通知 得到返回结果
public void afterReturning(JoinPoint joinPoint,int returnValue){
String name = joinPoint.getSignature().getName();
System.out.println("The "+name+" method ends whith "+returnValue);
}
@AfterThrowing(value = "execution(* com.ganin.aop.after.*.*(..))",throwing = "e") //只有发生异常时才会执行
public void afterThrowing(Exception e){
System.out.println(e.getMessage());
}
}
5.在application.xml中开启切面注解
<!--开启面向切面注解-->
<mvc:aspectj-autoproxy/>
6.测试
public static void main(String[] args) {
//读取配置文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("application.xml");
ArithmeticCalculator impl = (ArithmeticCalculator) applicationContext.getBean("arithmeticCalculatorImpl");
int add = impl.div(10, 0);//除法运算(此时 afterThrowing中异常会执行) 看下图1
System.out.println(add);
}
此时 我们改一下 传入一个合法的值 看图
此时 就测试成功了!!!!!!