AOP有5種通知:
@Before:前置通知臣镣,在方法執(zhí)行之前通知
@After:后置通知,在方法執(zhí)行之后通知
@AfterRunning:返回通知溯街,在方法返回結(jié)果之后通知
@AfterThrowing:異常通知匹中,在方法出現(xiàn)異常之后通知
@Around:環(huán)繞通知,環(huán)繞著方法通知
AOP開發(fā)除了官方下載的包外需要添加兩個(gè)jar包
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
切面 = 通知 + 切入點(diǎn)
這里只講@Before和@Around
寫一個(gè)UserDao接口和UserDaoImpl實(shí)現(xiàn)類朱浴,在實(shí)現(xiàn)類中寫一個(gè)read()方法作為切入點(diǎn)
package com.hello.dao;
public interface UserDao {
public void read();
}
package com.hello.dao.impl;
import org.springframework.stereotype.Component;
import com.hello.dao.UserDao;
@Component("userDao")
public class UserDaoImpl implements UserDao {
@Override
public void read() {
System.out.println("UserDao中的read()方法");
}
}
在src目錄下添加applicationContext.xml
<?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.hello"/>
<!-- 加載自動(dòng)代理(切面) -->
<aop:aspectj-autoproxy/>
</beans>
生成一個(gè)切面Myplus類吊圾,在類中寫callPlus()和aroundMethod()作為擴(kuò)展方法
package com.hello.plus;
import org.aspectj.lang.ProceedingJoinPoint;
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("myPlus")
public class Myplus {
//切面 = 通知 + 切入點(diǎn)
@Before("execution(public void com.hello.dao.impl.UserDaoImpl.read())")
public void callPlus()
System.out.println("我是最強(qiáng)的。翰蠢。项乒。");
}
@Around("Myplus.dian()")
public void aroundMethod(ProceedingJoinPoint joinPoint){
System.out.println("around--------前");
try {
joinPoint.proceed();
} catch (Throwable e) {
e.printStackTrace();
}
System.out.println("around--------后");
}
//切入點(diǎn)
@Pointcut(value="execution(* *..*.*Impl.read())")
public void qieRuDIan(){
}
}
1、在callPlus()方法中
@Aspect:注解表示這個(gè)類作為一個(gè)切面類
@Component("myPlus"):表示將這個(gè)類方法IOC中梁沧,也就是交給Spring管理
切面 = 通知 + 切入點(diǎn)
@Before:前置通知
("execution(public void com.hello.dao.impl.UserDaoImpl.read())"):切入點(diǎn)
2檀何、在aroundMethod()中
@Around:環(huán)繞通知
("Myplus.dIan()"):調(diào)用該類中的dian()方法獲得切入點(diǎn)
參數(shù) ProceedingJoinPoint joinPoint:聲明一個(gè)joinPoint對象
joinPoint.proceed():在 read() 執(zhí)行前執(zhí)行 joinPoint.proceed() 前的代碼,在 read() 執(zhí)行后執(zhí)行 joinPoint.proceed() 后的代碼廷支。
執(zhí)行結(jié)果: