Spring中AOP使用注解

注解和标签进行实现AOP,原理是一模一样的

  • @Before前置通知
  • @AfterReturning后置通知
    AfterReturningAdvice
  • @Around环绕通知
  • @AfterThrowing抛出通知
  • @After最终final通知,不管是否异常,该通知都会执行
  • @DeclareParents引介通知

1. 前提需要进行的配置,进行导入依赖和引入命名空间

2. 在xml文件里面开启注释描述

前两个是开启生成bean的注释扫描,第三个是开启AOP的注释描述

	<context:annotation-config/> 
	<context:component-scan base-package="com.hisoft"/>
	<aop:aspectj-autoproxy/>

3. 创建接口和实现类

接口

public interface StudentService {
	void addStudent();
}

实现类,实现接口,并使用注解生成bean

@Service
public class StudentServiceImpl implements StudentService{
	@Override
	public void addStudent() {
		System.out.println("添加学生");
	}
}

4. 编写通知类

(注意:里面的使用到了标签后,需要添加使用的范围)
通知类 添加@Aspect 注解,代表这是一个切面类,并将切面类交给spring管理(能被spring扫描到@Component)。

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
	生成bean和添加@Aspect注解
	//通知类,就是一 个普通的pojo类
	//将这个增强的类交给了spring管理了
@Component("aopDemo")
@Aspect //是一个切面类相当于<aop:aspect ref= ”myAspect">
public class AopDemo {
	@Before("bean(*Service)")
	public void before() {
		System.out.println("前置方法");
	}

	@AfterReturning(value = "target(com.hisoft.service.impl.StudentServiceImpl))",returning = "rv")
	public void after1(JoinPoint joinPoint,Object rv) {
		System.out.println("当前运行的类是"+joinPoint.getTarget().getClass().getName()+"运行的方法名为:"+joinPoint.getSignature().getName());
		System.out.println("返回值为:"+rv);
	}
	@Around("execution(* com.hisoft.service.impl.StudentServiceImpl.*(..))")
	public void around(ProceedingJoinPoint pd) throws Throwable {
		System.out.println("环绕头");
		Object object = pd.proceed();
		System.out.println("环绕尾");
	}
	@AfterThrowing(value="within(com.hisoft.service.impl.*)",throwing = "ex")
	public void afterTrowing(JoinPoint joinPoint,Throwable ex) {
		System.out.println(
				"亲爱的管理员,目前系统出现异常,请及时处理,发生异常的类是"
				+joinPoint.getTarget().getClass().getName()
				+",发生异常的方法为:"
				+joinPoint.getSignature().getName()
				+",异常信息为:"
				+ex.getMessage()
				);
	}
	@After("bean(*Service)")
	public void afterFinally() {
		System.out.println("这是一个最终通知");
	}
}

5. 测试

public class UserTest {
	public static void main(String[] args) {
		ApplicationContext app =new ClassPathXmlApplicationContext("applicationContext.xml");
		StudentService ss = (StudentService) app.getBean("studentService");
		ss.addStudent();
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值