Day32——基于XML配置AOP

一. 回顾

前面讲到了使用注解配置AOP,今天讲述使用XML方式配置AOP

本文章项目源码已经上传到本博客的“资源”处,有需要可前往免费下载

二. 知识储备

使用XML方式,所以要把某些注释删掉,比如@Aspect。

三. 例子

使用XML方式配置aop,实现日志功能。

ArithmeticCalculator.java

package com.atguigu.spring.aop.aspectJ_xml;

/**
 * 算数计算器
 * @author user
 *
 */
public interface ArithmeticCalculator {
    /**
     * 加法
     * @param i
     * @param j
     * @return
     */
	public int add(int i, int j);
	
	/**
	 * 减法
	 * @param i
	 * @param j
	 * @return
	 */
	public int sub(int i, int j);
	
	/**
	 * 乘法
	 * @param i
	 * @param j
	 * @return
	 */
	public int mul(int i, int j);
	
	/**
	 * 除法
	 * @param i
	 * @param j
	 * @return
	 */
	public int div(int i, int j);
	
}

ArithmeticCalculatorImpl.java

package com.atguigu.spring.aop.aspectJ_xml;


public class ArithmeticCalculatorImpl implements ArithmeticCalculator {

	@Override
	public int add(int i, int j) {
		// TODO Auto-generated method stub
		int result = i + j;
		return result;
	}

	@Override
	public int sub(int i, int j) {
		// TODO Auto-generated method stub
		int result = i - j;
		return result;
	}

	@Override
	public int mul(int i, int j) {
		// TODO Auto-generated method stub
		int result = i * j;
		return result;
	}

	@Override
	public int div(int i, int j) {
		// TODO Auto-generated method stub
		int result = i / j;
		return result;
	}

}

LoggingAspect.java

package com.atguigu.spring.aop.aspectJ_xml;

import java.util.Arrays;

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

/**
 * 切面:日志切面
 * @author user
 *
 */
public class LoggingAspect {

	public void beforeMethod(JoinPoint joinPoint) {
		
		//方法名
		String methodName = joinPoint.getSignature().getName();
		
		//方法的参数列表
		Object[] args = joinPoint.getArgs();
		
		System.out.println("LoggingAspect==> The method " + methodName + " begin with : " + Arrays.asList(args));
		
	}
	
	
	public void afterMethod(JoinPoint joinPoint) {
		String methodName = joinPoint.getSignature().getName();
		System.out.println("LoggingAspect==> The method " + methodName + " ends.");
	}
	
	
	
	public void afterThrowingMethod(JoinPoint joinPoint, Exception ex) {
		//获取方法名
		String methodName = joinPoint.getSignature().getName();
		System.out.println("LoggingAspect==> The method " + methodName + " occurs Exception: " + ex);
	}
	
	
	public void afterReturningMethod(JoinPoint joinPoint, Object result) {
		String methodName = joinPoint.getSignature().getName();
		System.out.println("LoggingAspect==> The method " + methodName + "ends with: " + result);
	}
	
	
	public Object aroundMethod(ProceedingJoinPoint pjp) {
	
		try {
			//前置
			
			
			//调用目标方法
			Object result = pjp.proceed();
			
			
			//返回
			return result;
			
			
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			//异常
			e.printStackTrace();
		}finally {
			//后置
		}
	
		return null;
	
	}
	
	
}

ValidationAspect.java

package com.atguigu.spring.aop.aspectJ_xml;

import java.util.Arrays;
import org.aspectj.lang.JoinPoint;

/**
 * 验证切面
 * @author user
 *
 */
public class ValidationAspect {
    
	public void beforeMethod(JoinPoint joinPoint) {
		String methodName = joinPoint.getSignature().getName();
		Object[] args = joinPoint.getArgs();
		System.out.println("ValidationAspect==> The method " + methodName + " begin with : " + Arrays.asList(args));
		
	}
}

Main.java

package com.atguigu.spring.aop.aspectJ_xml;

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

public class Main {
         public static void main(String[] args) {
        		ApplicationContext ctx = 
        				new ClassPathXmlApplicationContext("spring-aop_xml.xml");
        		
        		ArithmeticCalculator  ac = 
        				ctx.getBean("arithmeticCalculatorImpl",ArithmeticCalculator.class);
        		
        		System.out.println("ac: " + ac.getClass().getName());
        		
        		int result = ac.add(1, 1);
        		
        		System.out.println("Main===>: " +result );
        		
        		System.out.println("============================================================='");
        		
		}
}

注意:=如果报错,那么99%都是xml里面的bean配置写错了,因为只要有一个bean配置不成功,都会报错。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring AOPSpring框架中的一个重要模块,它提供了面向切面编程(AOP)的支持。AOP是一种编程思想,它可以在不改变原有代码的情况下,通过在程序运行时动态地将代码“织入”到现有代码中,从而实现对原有代码的增强。 Spring AOP提供了基于注解的AOP实现,使得开发者可以通过注解的方式来定义切面、切点和通知等相关内容,从而简化了AOP的使用。 下面是一个基于注解的AOP实现的例子: 1. 定义切面类 ```java @Aspect @Component public class LogAspect { @Pointcut("@annotation(Log)") public void logPointcut() {} @Before("logPointcut()") public void beforeLog(JoinPoint joinPoint) { // 前置通知 System.out.println("执行方法:" + joinPoint.getSignature().getName()); } @AfterReturning("logPointcut()") public void afterLog(JoinPoint joinPoint) { // 后置通知 System.out.println("方法执行完成:" + joinPoint.getSignature().getName()); } @AfterThrowing(pointcut = "logPointcut()", throwing = "ex") public void afterThrowingLog(JoinPoint joinPoint, Exception ex) { // 异常通知 System.out.println("方法执行异常:" + joinPoint.getSignature().getName() + ",异常信息:" + ex.getMessage()); } } ``` 2. 定义业务逻辑类 ```java @Service public class UserService { @Log public void addUser(User user) { // 添加用户 System.out.println("添加用户:" + user.getName()); } @Log public void deleteUser(String userId) { // 删除用户 System.out.println("删除用户:" + userId); throw new RuntimeException("删除用户异常"); } } ``` 3. 在配置文件中开启AOP ```xml <aop:aspectj-autoproxy/> <context:component-scan base-package="com.example"/> ``` 在这个例子中,我们定义了一个切面类LogAspect,其中通过@Aspect注解定义了一个切面,通过@Pointcut注解定义了一个切点,通过@Before、@AfterReturning和@AfterThrowing注解分别定义了前置通知、后置通知和异常通知。 在业务逻辑类中,我们通过@Log注解标注了需要增强的方法。 最后,在配置文件中,我们通过<aop:aspectj-autoproxy/>开启了AOP功能,并通过<context:component-scan>扫描了指定包下的所有组件。 这样,当我们调用UserService中的方法时,就会触发LogAspect中定义的通知,从而实现对原有代码的增强。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值