spring_由注解实现AOP面向切面编程_实现动态代理

来源:互联网 发布:家用音响 知乎 编辑:程序博客网 时间:2024/06/05 21:14

新加Jar包:

spring-aop-4.0.0.RELEASE.jar
aopalliance-1.0.jar
aspectjrt.jar
aspectjweaver.jar

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans.xsd         http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context.xsd         http://www.springframework.org/schema/aop          http://www.springframework.org/schema/aop/spring-aop.xsd"><context:annotation-config /><context:component-scan base-package="com.bjsxt" /><!-- aspectj是一个专门实现代理的框架(面向切面编程)spring使用了它 --><aop:aspectj-autoproxy /></beans>

package com.bjsxt.aop;import org.aspectj.lang.ProceedingJoinPoint;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.aspectj.lang.annotation.Pointcut;import org.springframework.stereotype.Component;@Aspect// 中文:切面@Component("logInterceptro")// 中文:组件// 初始化logInterceptro,交给bean管理public class LogInterceptro {@Pointcut("execution(public * com.bjsxt.dao..*.*(..))")// @Pointcut("execution(public * com.bjsxt.service..*.*(..))")// 中文:切入点// 如果在无接口类加切入逻辑,加入cglib-2.2.jar包,来帮这个类产生二进制动态代理// 定义一系列切入点的集合,给这个切入点集合起了个叫"myMethod()"这个方法名public void myMethod() {}@Before("myMethod()")// 中文:之前// public 任何返回值 com.bjsxt.dao.包及子包(".."相当于子包下子包...).任何类.任何方法(任何参数){public *// com.bjsxt.dao..*.*(..)}// 把这个逻辑织入到原来的哪个方法中去// 在方法执行之前先执行我这个方法(织入)// 哪个对象必须得是spring管理起来的public void beforeMethod() {System.out.println("method brefore");}@AfterReturning("myMethod()")// 中文:后,返回这个方法// 所有方法正常执行完成后,切入该逻辑public void AfterReturningMethod() {System.out.println("method after returning");System.out.println("---------------");}@AfterThrowing("myMethod()")// 中文:方法执行后,抛出异常// 只要有方法抛出异常,切入该逻辑public void AfterThrowingMethod() {System.out.println("method after throwing");System.out.println("---------------");}@Around("myMethod()")// 中文:程序的连接点,环绕切入点// 只要有方法抛出异常,切入该逻辑public void AroundMethod(ProceedingJoinPoint pjp) throws Throwable {System.out.println("=========================");System.out.println("method around start");pjp.proceed();System.out.println("method around end");}}

package com.bjsxt.dao.impl;import org.springframework.stereotype.Component;import com.bjsxt.dao.UserDao;import com.bjsxt.model.User;@Component("userDaoImpl")public class UserDaoImpl implements UserDao {@Overridepublic void save(User user) {System.out.println("user save!");// throw new RuntimeException("exception");}}