一晒喷、AOP的基本概念:
(1)Aspect(切面):通常是一個(gè)類孝偎,里面可以定義切入點(diǎn)和通知
(2)JointPoint(連接點(diǎn)):程序執(zhí)行過程中明確的點(diǎn),一般是方法的調(diào)用
(3)Advice(通知):AOP在特定的切入點(diǎn)上執(zhí)行的增強(qiáng)處理厨埋,有before,after,afterReturning,afterThrowing,around
(4)Pointcut(切入點(diǎn)):就是帶有通知的連接點(diǎn)邪媳,在程序中主要體現(xiàn)為書寫切入點(diǎn)表達(dá)式
(5)AOP代理:AOP框架創(chuàng)建的對(duì)象,代理就是目標(biāo)對(duì)象的加強(qiáng)荡陷。Spring中的AOP代理可以使JDK動(dòng)態(tài)代理雨效,也可以是CGLIB代理,前者基于接口废赞,后者基于子類
二徽龟、 spring AOP
Spring中的AOP代理還是離不開Spring的IOC容器,代理的生成唉地,管理及其依賴關(guān)系都是由IOC容器負(fù)責(zé)据悔,Spring默認(rèn)使用JDK動(dòng)態(tài)代理传透,在需要代理類而不是代理接口的時(shí)候,Spring會(huì)自動(dòng)切換為使用CGLIB代理极颓,不過現(xiàn)在的項(xiàng)目都是面向接口編程朱盐,所以JDK動(dòng)態(tài)代理相對(duì)來說用的還是多一些。
三菠隆、例子
創(chuàng)建一個(gè)接口
public interfance Move {
void move()兵琳;
創(chuàng)建Tank類實(shí)現(xiàn)接口
public class Tank implements Move {
@Override
public void move() {
System.out.println("tank is moving");
}
}
創(chuàng)建一個(gè)接口代理類
public class MoveProxy implements Move {
//聲明一個(gè)Move接口的對(duì)象
private Move t;
public MoveProxy(Move t) {
this.t = t;
}
@Override
public void move() {
System.out.println("start");
t.move();
System.out.println("Stop");
}
}
創(chuàng)建MoveApp類創(chuàng)建對(duì)象實(shí)現(xiàn)方法
public class MoveApp {
public static void main(String[] args) {
Move t = new Tank();
Move moveproxy = new MoveProxy(t);
t.move();
}
}
通過IoC容器配置bean
創(chuàng)建一個(gè)接口
public interface Hello {
String getHello();
}
創(chuàng)建一個(gè)類實(shí)現(xiàn)接口方法
public class HelloImpl implements Hello {
@Override
public String getHello() {
return "Hello, spring aop";
}
}
加一個(gè)前置增強(qiáng)
public class BeforeAdvice {
private static final Logger logger = (Logger) LoggerFactory.getLogger(BeforeAdvice.class);
public void beforeMethod(){
logger.debug("連接數(shù)據(jù)庫");
}
}
在xml配置bean
<!--<!–配置一個(gè)Hello的類–>-->
<bean id="hello" class="com.spring.AoP.HelloImpl"/>
<!--<!–配置一個(gè)MyBeforeAdvice前值增前的類–>-->
<bean id="myBeforeAdvice" class="com.spring.AoP.MyBeforeAdvice"/>
<!--<!–配置aop–>-->
<aop:config>
<aop:aspect id="before" ref="myBeforeAdvice">
<aop:pointcut id="myPointCut" expression="execution(* com.spring.AoP.*.*(..))"/>
<aop:before method="beforeMethod" pointcut-ref="myPointCut"/>
</aop:aspect>
</aop:config>