spring AOP

来源:互联网 发布:centos修改sftp端口 编辑:程序博客网 时间:2024/06/05 14:16
在pom. xml中配置如下jar包<dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>4.3.12.RELEASE</version></dependency><dependency>  <groupId>aopalliance</groupId>  <artifactId>aopalliance</artifactId>  <version>1.0</version></dependency><dependency>  <groupId>aspectj</groupId>  <artifactId>aspectjweaver</artifactId>  <version>1.5.3</version></dependency>在spring.xml中配置xmlns:aop="http://www.springframework.org/schema/aop"http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd<aop:config><!-- 定义切点(搜索条件)表达式  execution(返回值  包.类.方法(参数)) --><!-- 任意返回值   在lesson03.aop中的AfHouseOwner类中的所有seekMyHouse(..)方法   (..)表示任意参数--><aop:pointcut expression="execution(* lesson03.aop.AfHouseOwner.seekMyHouse(..))" id="myPointCut"/><aop:aspect ref="myMessage"><!-- 前置通知   调用方法前 --><aop:before method="beforeSeek" pointcut-ref="myPointCut"/><!-- 后置通知   调用方法后 --><aop:after method="afterSeek" pointcut-ref="myPointCut"/><!-- 异常通知   出现异常 --><aop:after-throwing method="throwException" pointcut-ref="myPointCut"/></aop:aspect></aop:config>


/切点
package lesson03.aop;import org.springframework.stereotype.Component;@Componentpublic class AfHouseOwner {    public void seekMyHouse() {       System.out.println("安防房东租房");       //异常       int i=5/0;    }}//通知类package lesson03.aop;import org.aspectj.lang.JoinPoint;import org.springframework.stereotype.Component;@Componentpublic class MyMessage {    public void beforeSeek(){        System.out.println("打扫卫生");    }        public void afterSeek(){        System.out.println("收钱");    }    public void throwException(JoinPoint jp){        System.out.println("出现异常");        //出现异常类        System.out.println(jp.getThis());        //出现错误的方法        System.out.println(jp.getSignature().getName());    }}//入口package lesson03.aop;import java.sql.SQLException;import org.springframework.context.ConfigurableApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class TestCotiner {    static ConfigurableApplicationContext context;    static{        context=new ClassPathXmlApplicationContext("lesson03/aop/spring.xml");    }    public static void main(String[] args) throws SQLException {       AfHouseOwner af=(AfHouseOwner) context.getBean("afHouseOwner");       af.seekMyHouse();        context.close();    }
}/