AOP

来源:互联网 发布:2个excel查找相同数据 编辑:程序博客网 时间:2024/05/10 00:45

Aop:

要实现Aop,要导入lib/j2ee/common-annotations.jar

在配置文件中需要

http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd

几个重要的概念:

切面:其实和类差不多,只是他里面放的都是切入点和前置,后置等通知

切入点:pointCut("execution(* pakage.className.method(..))")

规定要对那个类的方法进行切割

通知:

spring中的注解方法进行AOP的实现:

·注解方式配置AOP

1,在配置文件中写上: 

<aop:aspectj-autoproxy/><!-- 这里就相当于注册了一个aop的处理器 -->

2把切面的那个类和业务方法中的那个我们需要的类交给spring管理,使用在配置文件中使用<bean>来配置,也可以使用包的扫描来配置<context:component-scan base-package="hwt.aspect"/>

3,写一个切面:

@Aspect//切面

public class AspectClass {

@Pointcut("execution(* service.AopService.*(..))")

public void anyMethod(){}//声明一个切入点

@Pointcut("execution(* aop.Service4.*(..))")

public void anyMethod2(){}//可以声明多个切入点

//前置通知,可以得到这个要的调用的这个方法的参数

//一般可以用这个得到要调用的函数的传入参数

@Before("anyMethod() && args(name)"//这个name和下面接收参数一样

public void beforeMethod(String name){

System.out.println("我是前置通知"+name);

}

//后置通知,可以通过returning来得到要调用的方法的返回值

//可以得到要调用的方法的返回值

    // 这里是得到连接点的返回值,名字和下面的一样

@AfterReturning(pointcut="anyMethod()",returning="rs"

public void afterReturningMethod(String rs){

System.out.println("我是后置的方法");

}

//最终通知

@After("anyMethod()")

public void finallyMethod(){

System.out.println("我是最终的通知");

}

//例外通知

@AfterThrowing(pointcut="anyMethod2()",throwing="e")

public void exceptionMethod(RuntimeException e){

System.out.println(e.getMessage());

}

//环绕通知

@Around("anyMethod()")

public Object aroundMethod(ProceedingJoinPoint pjp) throws Throwable{

Object rsObject = null;

System.out.println("进入方法");

rsObject = pjp.proceed();

System.out.println("退出方法");

return rsObject;

}

}

执行的顺序:

前置通知-->环绕通知-->后置通知-->最终通知-->退出环绕通知

在调用方法的时候,会先通过spring产生一个代理对象,来对这个方法进行前后的处理


==================

·XMl中配置Aop

1,写一个普通的java类(就是对于上面的切面,不要写注解的java类,由xml里面来配置)
2,配置文件中可以这样写

//这里是用包的扫描的方法,也可以用配置<bean>的方法

  <context:component-scan base-package="hwt.service"/>

  <context:component-scan base-package="hwt.aspect"/>

//切面的配置

 <aop:config>

     <aop:aspect id="aps" ref="aspectXMLClass">

     <aop:pointcut id="mypt" expression="execution(* hwt.service.PersonService.*(..))"/>

     <!--  前置方法接受参数 -->

     <aop:beforepointcut="execution(* hwt.service.PersonService.*(..))and args(emp)"args-name=”empmethod="beforeMethod"/>

     <aop:around pointcut-ref="mypt" method="aroundMethod"/>

     <aop:after-returning pointcut-ref="mypt" method="afterReturnMethod" returning="results"/>

     <aop:after pointcut-ref="mypt" method="afterMethod"/>

     </aop:aspect>

    </aop:config>



原创粉丝点击