AOP(面向切面编程)基于XML方式配置

 概念解释:(理解基本概念方可快速入手)

  1. 连接点(joinpoint)

    被拦截到的点,因为Spring只支持方法类型的连接点,所以在Spring中连接点指的就是被拦截到的方法。

  2. 切入点(pointcut)

    切入点是指我们要对哪些连接点进行拦截的定义

  3. 通知(advice)

    所谓通知指的就是指拦截到连接点之后要执行的代码,通知分为前置、后置、异常、最终、环绕通知五类

  4. 切面(aspect)

    是切入点和通知的结合

AOP(面向切面编程)基于XML方式配置_第1张图片

 通知顺序:

前置通知:aop:before
            后置通知:aop:after-returning【try】
            最终通知:aop:after【finally】
            异常通知:aop:after-throwing【catch】
            环绕通知:aop:around


            try{
                ...
                return aop:after-returning
            }catch(Exception e){
                ...
                aop:after-throwing
            }finally{
                ...
                aop:after
            }

切点表达式:
        格式:execution([修饰符] 返回值 报名.类名.方法名(参数))
        eg:execution(* com.by.service.*.*(..))

 实例演示:

pom.xml:


        
        
            org.springframework
            spring-context
            6.0.12
        
        
        
            org.springframework
            spring-aspects
            5.1.8.RELEASE
        
        
            org.slf4j
            slf4j-log4j12
            1.7.19
        
    

UserDaoImpl:

package com.by.dao;

public class UserDaoImpl implements UserDao {

    @Override
    public void addUser(){
        System.out.println("insert into tb_user......");
    }
}

UserServiceImpl:

package com.by.service;

import com.by.dao.UserDao;

public class UserServiceImpl implements UserService {

    private UserDao userDao;
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public void addUser(){
        userDao.addUser();
        System.out.println(8/0);
    }
}

MyLogActive:(增强类)

/*
 * Copyright (c) 2020, 2024,  All rights reserved.
 *
 */
package com.by.advice;

import org.aspectj.lang.ProceedingJoinPoint;

/**
 * 

Project: Spring - MyLogAdvice

*

Powered by scl On 2024-01-05 15:04:11

*

描述:

* * @author 孙臣龙 [[email protected]] * @version 1.0 * @since 17 */ public class MyLogAdvice { public void after() { System.out.println("最终通知、、、"); } public void before() { System.out.println("前置通知、。、"); } public void afterReturn(){ System.out.println("后置通知"); } public void afterThrowing(){ System.out.println("异常通知"); } public void around(ProceedingJoinPoint joinPoint) { try { System.out.println("前环绕通知。。。"); joinPoint.proceed(); System.out.println("后环绕通知。。。"); } catch (Throwable e) { throw new RuntimeException(e); } } }

 applicationContext.xml:




    
    
        
    
    
    
    
    
        
        
        
        
            
            
            
            
            
         
    

没增强前结果展示:

AOP(面向切面编程)基于XML方式配置_第2张图片

增强之后结果展示:

AOP(面向切面编程)基于XML方式配置_第3张图片

你可能感兴趣的:(java,开发语言)