转:SpringAop中@Before、@After、@Around执行顺序
首先说明,SpringAop需要有aspectjweaver这个依赖,要先加入到maven中;
@Component public class HelloWorld { public void sayHello (){ System.out.println("Hello World!"); } }
接下来需要声明切面,切点,通知,一样需要在spring的ioc容器内,且需要@Aspect注解,
@Aspect是让spring对该进行aop扫描,这样才能扫描到该类内部的切点、通知的注解,如下:
@Aspect @Component public class HelloWorldAspect { @Pointcut(value = "execution(* aop..sayHello(..))") public void pointCut (){ } @Before(value = "pointCut()") private void beforeAdvice (){ System.out.println("===========before advice param:"); } @After( value = "pointCut()") private void afterAdvice (){ System.out.println("===========after advice param:"); } @Around(value = "pointCut()") private void aroundAdvice (ProceedingJoinPoint pjp) throws Throwable{ System.out.println("===========before advice param: around"); pjp.proceed(); System.out.println("===========after advice param: around"); } }
这样一来,我们就完成了切点匹配,前置、后知、环绕通知的声明,然后就可以进行测试了
测试代码如下:
@Test public void testAop (){ ApplicationContext ctx = new AnnotationConfigApplicationContext(AopConfig.class); HelloWorld hw = ctx.getBean(HelloWorld.class); hw.sayHello(); }
输出的结果如下:
===========before advice param: around ===========before advice param: Hello World! ===========after advice param: around ===========after advice param:
所以我们得到结果:
前置时 环绕通知 -> 前置通知
后置时 环绕通知 -> 后置通知
另外spring中还有@AfterReturning、@AfterThrowing,这些将在下一次再写了,如果想早点看的话,可以参考下面的这个链接:
http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle
相关推荐
yupi0 2020-10-10
spring 2020-08-18
编程点滴 2020-07-29
幸运小侯子 2020-07-05
itjavashuai 2020-07-04
qingjiuquan 2020-06-29
shushan 2020-06-25
小鱿鱼 2020-06-22
咻pur慢 2020-06-18
melonjj 2020-06-17
qingjiuquan 2020-06-13
neweastsun 2020-06-05
小鱿鱼 2020-06-05
mxcsdn 2020-05-31
吾日五省我身 2020-05-27
牧场SZShepherd 2020-05-27
sweetgirl0 2020-05-14