1,前置通知;

2,后置通知;

3,环绕通知;

4,返回通知;

5,异常通知;

    1.1定义一个接口

  

package com.java.test6;

/**
 * @author nidegui
 * @create 2019-06-23 9:40
 */
public interface Student {
    public void addStudent(String name);
}

 

实现

package com.java.test6;

/**
 * @author nidegui
 * @create 2019-06-23 9:41
 */
public class StudentImpl implements  Student {
    @Override
    public void addStudent(String name) {
        System.out.println("添加学生"+name);
    }
}

  

在添加学生之前添加一个切点

package com.java.test6;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

/**
* @author nidegui
* @create 2019-06-23 9:45
*/
public class StudentServiceAspect {
//前置通知,在方法之前通知
public void before(JoinPoint jp){
System.out.println("类名:"+jp.getTarget().getClass().getName());
System.out.println("方法名:"+jp.getSignature().getName());
System.out.println("开始添加学生:"+jp.getArgs()[0]);

System.out.println("开始添加学生");
}
  //后置通知
public void doAfter(JoinPoint jp){
System.out.println("类名:"+jp.getTarget().getClass().getName());
System.out.println("方法名:"+jp.getSignature().getName());
System.out.println("学生添加完成:"+jp.getArgs()[0]);
}
//环绕通知
public Object doAround(ProceedingJoinPoint pjp) throws Throwable{
System.out.println("添加学生前");
Object retVal=pjp.proceed();
System.out.println(retVal);
System.out.println("添加学生后");
return retVal;
}
  //返回通知
public void doAfterReturning(JoinPoint jp){
System.out.println("返回通知");
}
  //异常通知
public void doAfterThrowing(JoinPoint jp,Throwable ex){
System.out.println("异常通知");
System.out.println("异常信息:"+ex.getMessage());
}


}

  

在配置文件中配置

<?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">


<bean />

</aop:aspect>
</aop:config>
</beans>

  

测试:

package com.java.test6;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author nidegui
 * @create 2019-06-22 14:47
 */
public class Test {
    public static void main(String[] args) {
       ApplicationContext ac = new ClassPathXmlApplicationContext("beanss.xml");

        Student people =(Student) ac.getBean("studentImpl");
        people.addStudent("zhangsna");

    }
}

spring aop实例

 

相关文章:

  • 2022-01-21
  • 2021-12-09
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-17
  • 2021-08-23
  • 2021-07-03
猜你喜欢
  • 2022-01-07
  • 2021-06-24
  • 2021-09-13
  • 2021-10-02
  • 2021-06-10
  • 2022-02-27
  • 2021-06-24
相关资源
相似解决方案