1. 程式人生 > >Spring AOP @Around @Before @After 區別

Spring AOP @Around @Before @After 區別

npoi -i ati all mini destroy 3.0 ota classpath

此段小代碼演示了spring aop中@Around @Before @After三個註解的區別@Before是在所攔截方法執行之前執行一段邏輯。@After 是在所攔截方法執行之後執行一段邏輯。@Around是可以同時在所攔截方法的前後執行一段邏輯。

package com.itsoft.action;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;

/**
 * 
 * 
@author zxf * 演示aop測試類 */ @Controller public class UserAction { public void queryUsers(){ System.out.println("查詢所有用戶【all users list】"); } public static void main(String[] args) { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("application-aop.xml"); UserAction userAction
= (UserAction)ctx.getBean("userAction"); userAction.queryUsers(); ctx.destroy(); } }
package com.itsoft;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
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; /** * * @author Administrator * 通過aop攔截後執行具體操作 */ @Aspect @Component public class LogIntercept { @Pointcut("execution(public * com.itsoft.action..*.*(..))") public void recordLog(){} @Before("recordLog()") public void before() { this.printLog("已經記錄下操作日誌@Before 方法執行前"); } @Around("recordLog()") public void around(ProceedingJoinPoint pjp) throws Throwable{ this.printLog("已經記錄下操作日誌@Around 方法執行前"); pjp.proceed(); this.printLog("已經記錄下操作日誌@Around 方法執行後"); } @After("recordLog()") public void after() { this.printLog("已經記錄下操作日誌@After 方法執行後"); } private void printLog(String str){ System.out.println(str); } }
<?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:aop="http://www.springframework.org/schema/aop"
      xmlns:context="http://www.springframework.org/schema/context"
      xsi:schemaLocation="
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/aop 
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
    <context:annotation-config />
    <context:component-scan base-package="com.itsoft"/>
    <aop:aspectj-autoproxy />
</beans>

代碼demo SVN svn://gitee.com/rainyn/SSM

參考轉自 http://outofmemory.cn/code-snippet/3025/spring-AOP-Around-Before-After-differentiate

Spring AOP @Around @Before @After 區別