您的位置:首页 > 编程语言 > Java开发

Spring——AOP核心思想与实现

2017-07-26 16:03 351 查看
AOP(Aspect Oriented Programming):面向切面编程

核心思想:动态的添加和删除切面上的逻辑而不影响原来的执行代码

AOP相关概念:

1.JoinPoint

连接点,加入切面逻辑的位置。

@Before("execution(* com.spring.service..*.*(..))")


2.PointCut

JoinPoint的一个集合

@Pointcut("execution(* com.spring.service..*.*(..))")
public void myMethod(){};

@Before("myMethod()")
public void before(){
System.out.println("before");
}


3.Aspect

指切面类,@Aspect

4.Advice

切面点上的业务逻辑

@Before;@AfterReturning;@Around ;…

5.Target

被代理对象

6.Weave

织入。将切面逻辑添加到原来执行代码上的过程。

AOP概念图



Spring中AOP的实现

1.Annotation

<!-- 找到被注解的切面类,进行切面配置 aop Annotation方法-->
<aop:aspectj-autoproxy/>


@Aspect
@Component
public class LogInterceptor {

@Pointcut("execution(* com.spring.service..*.*(..))") public void myMethod(){}; @Before("myMethod()") public void before(){ System.out.println("before"); }

@Around("execution(* com.spring.dao.impl..*.*(..))")
public void
4000
aroundProcess(ProceedingJoinPoint pjp) throws Throwable{
System.out.println("around before");
pjp.proceed();
System.out.println("around after");
}

}


2.xml

<!-- aop xml方法 -->
<bean id="logInterceptor" class="com.spring.aop.LogInterceptor"/>
<aop:config>
<aop:pointcut id="logPointcut"
expression="execution(* com.spring.service..*.*(..))"/>

<aop:aspect id="logAspect" ref="logInterceptor">
<aop:before method="before" pointcut-ref="logPointcut"/>
</aop:aspect>

</aop:config>


AOP原理解析

Spring AOP主要通过动态代理实现。Struts2中的interceptor就是AOP的一种实现。

动态代理

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: