spring3.0 - AOP編程

瞭解一下基礎知識:
切面(Aspect):關注點的模塊化,關注點可能橫切多個對象
連接點(Join point): 運用程序執行過程中需要入插切面模塊的某一點, 主要強調的是一個具體的”點”
概念,該點可以是一個方法、一個屬性、構造函數、類靜態初始化塊,甚至一條語句。
切入點(Pointcut):一個或多個連接點,可以理解成一個點的集合
通知(Advice):定義切面中實際的邏輯實現,如日誌的寫入實際代碼,或是安全檢查的實際代碼。
 前置通知(before advice):在方法的調用之前
 最終通知(after advice):在方法的最後,並且在所有其它通知之後
 環繞通知(around advice):分別在方法的調用之前和之後
 後置通知(after returning advice):在方法的最後
 異常通知(after throwing advice):在方法出現異常時

第一步,導入相關的jar包:aspectjweaver-1.6.8.jar(提供註解org.aspectj.lang.annotation.Aspect等)、spring-aop-3.0.4.RELEASE.jar(提供自動代理創建器org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator)、aopalliance-1.0.jar(提供攔截器功能)。
第二步,配置springMVC-servlet.xml
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"

<!--配置aop自動創建代理-->
<aop:aspectj-autoproxy/>
<bean id="aopSecurity" class="com.aliks.test.aop.util.SecurityHandlerAOP"/>

第三步,AOP類處理
@Component
@Aspect
public class SecurityHandlerAOP {
private int num=0;
// 在執行指定方法前執行
@Before("execution(* com.aliks.test.mvc.service.*.*(..))")
protected void checkUserSecurity() {
System.out.println("在方法執行前通知!");
num++;
System.out.println("訪問次數:"+num);
}

@After("execution(* com.aliks.test.mvc.service.*.*(..))")
protected void checkResult() {
System.out.println("在方法執行後通知!");
}

}
第四步,需要切面的類和方法
@Service("userManager")
public class UserManagerImpl implements UserManager {

@Override
public void addUser(String name) {
System.out.println("add user name:"+name);

}
第五步:controller層請求進入
@Controller
public class HelloWoldController {
@Autowired
private UserManager userManager;

@RequestMapping("/hello")
public ModelAndView helloWold()
{
System.out.println("start");
String message =new ToolTest().getString();
//調用service層
//增加用戶名稱測試
userManager.addUser("admin Test");
return new ModelAndView("hello","message",message);
}
}
第六步:測試結果
在方法執行前通知!
訪問次數:1
add user name:admin Test
在方法執行後通知!


切入點(Pointcut):一個或多個連接點,可以理解成一個點的集合
// 使用一個返回值爲void,方法體爲空的方法來命名切入點
@Pointcut("execution(* com.aliks.test.mvc.service.*.*(..))")
private void check(){}
// 在執行指定方法前執行
@Before("check()")
protected void checkBefore() {
System.out.println("Before-在方法執行前通知!");
num++;
System.out.println("Before-訪問次數:" + num);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章