Spring AOP

来源:互联网 发布:蜂窝移动数据开启无效 编辑:程序博客网 时间:2024/06/05 03:16

Spring AOP is used in the Spring Framework to…

·  provide declarative enterprise services, especially asa replacement for EJB declarative services. The most important such serviceis declarative transaction management.

·  allow users to implement custom aspects, complementing their use of OOP with AOP。

一、Spring AOP concepts

1、Aspect 切面

@Aspect@Component("switchAspect")public class SwitchAspect {    @Pointcut("execution(* com.util.HUtils.*(..))")    public void pointCutMethod(){        }    @Before(value = "pointCutMethod()")     public  void doBefore(JoinPoint joinPoint) {      System.out.println("请求方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));                  }        @Around("pointCutMethod()")    public Object doAround(ProceedingJoinPoint pj) throws Throwable {        System.out.println("开始doAround:"+pj);        Object result = null;        if(SwitchManager.on){            result = pj.proceed();        }        System.out.println("结束doAround,result="+result);        return result;    }}
如上SwitchAspect类就是定义的一个切面,切面(类)中执行的方法将横切到所有满足切入点PointCut 中匹配通配符的所有类、方法。可使用@Aspect 或者xml配置文件的方式声明一个切面。

<bean id="myAspect" class="org.xyz.NotVeryUsefulAspect"><!-- configure properties of aspect here as normal --></bean>

值的注意的是

1、使用@Aspect后,对于切面类仍然需要@component来注入到spring容器中进行管理。@Aspect注解只起到声明切面的作用。

2、配置切面可用的方式

@Configuration@EnableAspectJAutoProxypublic class AppConfig {}
或者直接在spring配置文件中添加

<aop:aspectj-autoproxy/>
2、Join point  连接点

3、Advice 通知

4、PointCut 切入点

连接点、切入点、通知三者的关系,Advice is associated with a pointcut expression and runs at any join point matchedbythepointcut。通知和一个切入点表达式关联,并在满足这个切入点的连接点上运行(例如,当执行某个特定名称的方法时)。切入点表达式如何和连接点匹配是AOP的核心。

*PointCut切入点通常使用execution()通配符的方式来匹配需要拦截的目标类或者方法。

*满足这个通配符的所有方法入口都是一个连接点。

*切面中所有定义的方法,都会在符合这些通配符的地方进行连接,将切面和目标方法进行before、after、around等方式连接执行。而这个过滤筛选的通配符或者断言就是切入点。

5、Target object 目标对象

被一个或者多个切面(aspect)所通知(advise)的对象。也有人把它叫做被通知(advised)对象。 因为Spring AOP是通过运行时代理实现的,这个对象永远是一个被代理(proxied)对象。

6、AOP Proxy  AOP代理

AOP框架创建的对象,用来实现包括通知方法执行等功能)。在Spring中,AOP代理可以是JDK动态代理或者CGLIB代理。


0 0
原创粉丝点击