此文章演示为纯注解形式,如需注解形式请参考文章
1:引入AOP依赖
这里类的路径 org.example.AOP.aspect下的类
其他通知类型注解使用请看下面拓展演示
@Component// 将对象交给IOC容器去实例化@Aspect// 声明当前类是一个切面public class LogCut {//这里表示代理了 org.example包及子包下所有内容 @Pointcut("execution(* org.example..*.*(..))") public void cut(){} @Before(value = "cut()") public void before() { System.out.println("前置通知1....."); }}
3:创建一个被代理的java类这里类的路径 org.example.IOC.entiy 下的类
@Componentpublic class People implements Serializable { private String name; private Date bir; //省略get set 构造器等方法 public void init(){ System.out.println("一个新的人类出生了"); } public void destory(){ System.out.println(name+"他走了"); }}
4:设置SpringAOP配置类@Configuration//此注解表示当前类是一个配置类@ComponentScan(basePackages = {"org.example"}) //注解:表示扫描包 属性设置扫描包的范围@EnableAspectJAutoProxy(exposeProxy = true)//开启AOP代理public class SpringAop {}
5:代码测试@Test public void test01(){ ApplicationContext ann = new AnnotationConfigApplicationContext(SpringAop.class); People people01 = ann.getBean("people", People.class); people01.setName("zhangsan"); System.out.println("set设置名字"); }
恭喜你,完成了SpringAop搭建!如有问题请留言
分割线,拓展演示其他注解类型方法使用package org.example.AOP.aspect;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.*;import org.springframework.stereotype.Component;@Component// 将对象交给IOC容器去实例化@Aspect// 声明当前类是一个切面public class LogCut { @Pointcut("execution(* org.example..*.*(..))") public void cut(){} @Before(value = "cut()") public void before() { System.out.println("前置通知1....."); } @AfterReturning(value = "cut()") public void afterReturn() { System.out.println("返回通知....."); } @After(value = "cut()") public void after() { System.out.println("最终通知....."); } @AfterThrowing(value="cut()",throwing = "e") public void afterThrow(Exception e) { System.out.println("异常通知....." + " 异常原因:" + e.getCause()); } @Around(value = "cut()") public Object around(ProceedingJoinPoint pjp) { System.out.println("前置通知..."); Object object = null; try { object = pjp.proceed(); System.out.println(pjp.getTarget() + "======" + pjp.getSignature()); // System.out.println("返回通知..."); } catch (Throwable throwable) { throwable.printStackTrace(); System.out.println("异常通知..."); } System.out.println("最终通知..."); return object; }}