【AOP系列】(三)—采用Spring的注解(Annotation)实现AOP

前提

  这篇文章要采用注解的方式实现AOP,这种方式写起来很简单,但是需要具备对基础的概念的理解,大家可以参考上一篇博文【AOP系列】(二)—AOP相关概念 来回顾一下。

实现步骤

1、spring的依赖包配置(cglib的jar包可以不引用)

【AOP系列】(三)—采用Spring的注解(Annotation)实现AOP_第1张图片

2、将横切性关注点模块化,建立LogHandler.java

3、采用注解指定LogHandler为Aspect

4、采用注解定义Advice和Pointcut

package com.tgb.spring;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class LogHandler {
    /** * 定义Pointcut,PointCut的名称就是addAddMethod(),此方法没有返回值和参数 * 该方法就是一个标识,不进行调用 * execution是表达式,表示匹配哪类方法, * 第一个*:方法的返回值任意 * add* :表示方法只要以add开头就可 * .. :表示方法的参数任意 */
    @Pointcut("execution(* add*(..))")
    private void addAddMethod(){};
    /* * 定义Advice * Before表示Advice在目标方法的什么位置应用 * addAddMethod()表示按照这种Pointcut应用到JoinPoint上 */
    @Before("addAddMethod()")
    public void WriteLog(){
        System.out.println("打印日志……………………………………");
    }
}

5、启用AspectJ对Annotation的支持,并且将目标类和Aspect类配置到IoC容器中

<?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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

    <!--启用AspectJ对Annotation的支持 -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
    <bean id="userManager" class="com.tgb.spring.UserManagerImpl"></bean>
    <bean id="logHandler" class="com.tgb.spring.LogHandler"></bean>
</beans>

6、开发客户端

package com.tgb.spring;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Client {
    public static void main(String[] args){
        BeanFactory factory= new ClassPathXmlApplicationContext("applicationContext.xml");
        UserManager userManager=(UserManager)factory.getBean("userManager");
        userManager.addUser("1", "zhangsan");
    }
}

总结

★注解方式优点:

1、在class文件中,可以降低维护成本

2、提高开发效率。

★注解方式缺点:

1、如果对注解进行修改,需要重新编译整个工程。

2、程序中过多的annotation,对于代码的简洁度有一定影响。

你可能感兴趣的:(【AOP系列】(三)—采用Spring的注解(Annotation)实现AOP)