Spring-aop面向切面编程

来源:互联网 发布:知乎专栏 pytorch 编辑:程序博客网 时间:2024/06/07 19:57
  • Aop:面向切面编程
      • 1、首先写一个接口,2、写一个实现类,实现该接口,因为代理用的是同一类型3、例:后置通知:实现AfterReturningAdvice接口,此接口重写的方法参数:返回值,方法,参数,目标对象,前置通知:实现MethodBeforeAdvice 接口,该重写的方法不能没有返回值
      • Top:配置文件:1、配置创建的类的bean,配置aop:config—>切点 ,指添加切面的点<aop:pointcut id="pointcut"   expression="execution(* com.lanou.test.*.*(..))" />【 execution(* 返回值  com.lanou.springtest.* 包+类名 [.. 子包] .* 方法  (.. 参数))】2、通知器:<aop:advisor advice-ref="loggerbeforeadvice" pointcut-ref="pointcut"/> 
    • 注解Aop:
      • 1、创建一个类:@Aspect@Component 告诉spring该类是一个切面,                  2、写一个方法,上面加上@Pointcut("execution(* com.lanou.test.*.*(..))”),这个方法再实现通知方法是用,前置通知Before方法上加@Before((“这儿写上面写point cut的方法”,前置通知主要各种校验,       3、@AfterReturning("temp()")//常规数据处理                                                                        public void afterRunning(JoinPointpoint)                                                                @After("temp()")//释放资源,最后执行
      • public voidafter(){}                                                                                               @Around("temp()")//优先级比before高,可以改变参数
      • public voidaround(ProceedingJoinPointpjp){
      • Object[] param=pjp.getArgs();
      • param[0]="cuidengyi";
      • try {
      • System.out.println(pjp.proceed());
      • //pjp.proceed(param);//执行前置通知,有返回值
      • }catch (Throwablee) {
      • e.printStackTrace();
      • }}}
      • logger:日志:用于控制台输出提示:Log4JLogger logger=new Log4JLogger(this.getClass().getName());
        • logger.debug("有错误");
        • logger.fatal("非常严重");    
        •      注:需要在工程中加入:log4j.properties文件,在struts2下

原创粉丝点击