美文网首页
十、使用注解定义切面

十、使用注解定义切面

作者: lifeline张 | 来源:发表于2018-08-30 10:05 被阅读0次

    一、本课目标

    • 掌握使用注解实现AOP的方法

    二、使用注解定义切面

    2.1简介

    • AspectJ
      面向切面的框架,它扩展了Java语言,定义了AOP语法,能够在编译期提供代码的织入。
    • @AspectJ
      AspectJ5新增的功能,使用JDK5.0注解技术和正规的AspectJ切点表达式语言描述切面(所以在使用@AspectJ的时候,要保证所用的JDK是5.0或者以上的版本)
    • Spring通过集成AspectJ实现了以注解的方式定义增强类,大大减少了配置文件中的工作量
      利用轻量级的字节码处理框架asm处理@AspectJ中所描述的方法参数名

    2.2示例

    需求:使用注解来实现日志切面
    分析:
    1、使用注解定义前置增强和后置增强实现日志功能
    2、编写Spring配置文件,完成切面织入


    image.png

    实体类:

    package entity;
    
    /**
     * 用户实体类
     */
    public class User implements java.io.Serializable {
        private Integer id; // 用户ID
        private String username; // 用户名
        private String password; // 密码
        private String email; // 电子邮件
    
        // getter & setter
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        public String getEmail() {
            return email;
        }
    
        public void setEmail(String email) {
            this.email = email;
        }
    
    }
    

    增强类:

    package aop;
    
    import java.util.Arrays;
    
    import org.apache.log4j.Logger;
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Before;
    /**
     * 增强处理类
     * @author Administrator
     *
     */
    @Aspect
    public class UserServiceLogger {
        private static Logger log = Logger.getLogger(UserServiceLogger.class);
        
        @Before("execution(* service.UserService.*(..))")
        public void before(JoinPoint jp) {
            log.info("调用" + jp.getTarget() + "的" + 
                    jp.getSignature() + "方法,方法参数" +
                    Arrays.toString(jp.getArgs()));
        }
    
        public void afterReturning(JoinPoint jp, Object result) {
            log.info("调用" + jp.getTarget() + "的" + 
                    jp.getSignature() + "方法,方法返回值" +
                    result);
        }
    }
    

    dao层:

    package dao;
    
    import entity.User;
    
    /**
     * 增加DAO接口,定义了所需的持久化方法
     */
    public interface UserDao {
        public void save(User user);
    }
    
    package dao.impl;
    
    import org.springframework.stereotype.Repository;
    
    import dao.UserDao;
    import entity.User;
    
    /**
     * 用户DAO类,实现UserDao接口,负责User类的持久化操作
     */
    @Repository("userDao")
    public class UserDaoImpl implements UserDao {
    
        public void save(User user) {
            // 这里并未实现完整的数据库操作,仅为说明问题
            System.out.println("保存用户信息到数据库");
        }
    }
    

    service层:

    package service;
    
    import entity.User;
    
    /**
     * 用户业务接口,定义了所需的业务方法
     */
    public interface UserService {
        public void addNewUser(User user);
    }
    
    package service.impl;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.stereotype.Service;
    
    import service.UserService;
    import dao.UserDao;
    import entity.User;
    
    /**
     * 用户业务类,实现对User功能的业务管理
     */
    @Service("userService")
    public class UserServiceImpl implements UserService {
    
        // 声明接口类型的引用,和具体实现类解耦合
        private UserDao dao;
    
    /*  // 无参构造
        public UserServiceImpl() {
        }*/
    
        @Autowired
        // 指定装配的bean的名称
        public void setDao(@Qualifier("userDao")UserDao dao) {
            this.dao = dao;
        }
    
    
    /*  // 用于为dao属性赋值的构造方法
        public UserServiceImpl(UserDao dao) {
            this.dao = dao;
        }*/
    
        public void addNewUser(User user) {
            // 调用用户DAO的方法保存用户信息
            dao.save(user);
        }
    }
    

    配置文件:

    <?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-3.2.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
        <!-- 扫描包中注解标注的类 -->
        <context:component-scan base-package="service,dao" />
        <bean class="aop.UserServiceLogger"></bean>
        <!--  启动对Spring AOP的AspectJ注解的支持  -->
        <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
    </beans>
    

    测试类:

    package test;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import service.UserService;
    
    import entity.User;
    
    public class Test {
        
        @org.junit.Test
        public void test() {
            // 使用ApplicationContext接口的实现类ClassPathXmlApplicationContext加载Spring配置文件
            ApplicationContext ctx = new ClassPathXmlApplicationContext(
                    "applicationContext.xml");
            // 通过ApplicationContext接口的getBean()方法获取id或name为userService的Bean实例
            UserService service = (UserService) ctx.getBean("userService");
    
            User user = new User();
            user.setId(1);
            user.setUsername("test");
            user.setPassword("123456");
            user.setEmail("test@xxx.com");
    
            service.addNewUser(user);
        }
    }
    

    运行结果:


    image.png

    增加后置增强:

    package aop;
    
    import java.util.Arrays;
    
    import org.apache.log4j.Logger;
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.annotation.AfterReturning;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Before;
    /**
     * 增强处理类
     * @author Administrator
     *
     */
    @Aspect
    public class UserServiceLogger {
        private static Logger log = Logger.getLogger(UserServiceLogger.class);
        
        @Before("execution(* service.UserService.*(..))")
        public void before(JoinPoint jp) {
            log.info("调用" + jp.getTarget() + "的" + 
                    jp.getSignature() + "方法,方法参数" +
                    Arrays.toString(jp.getArgs()));
        }
    
        @AfterReturning(pointcut="execution(* service.UserService.*(..))",
                returning="result")
        public void afterReturning(JoinPoint jp, Object result) {
            log.info("调用" + jp.getTarget() + "的" + 
                    jp.getSignature() + "方法,方法返回值" +
                    result);
        }
    }
    

    运行结果:


    image.png

    注:有时候同一个切入点要在很多地方用到,这时候我们要进行统一的定义,以方便我们的重用和维护。
    代码如下:

    package aop;
    
    import java.util.Arrays;
    
    import org.apache.log4j.Logger;
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.annotation.AfterReturning;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Before;
    import org.aspectj.lang.annotation.Pointcut;
    /**
     * 增强处理类
     * @author Administrator
     *
     */
    @Aspect
    public class UserServiceLogger {
        private static Logger log = Logger.getLogger(UserServiceLogger.class);
        
        // 统一定义切入点,并定义该切入点的方法名
        @Pointcut("execution(* service.UserService.*(..))")
        public void pointcut() {}
        
        @Before("pointcut()")
        public void before(JoinPoint jp) {
            log.info("调用" + jp.getTarget() + "的" + 
                    jp.getSignature() + "方法,方法参数" +
                    Arrays.toString(jp.getArgs()));
        }
    
        @AfterReturning(pointcut="pointcut()",
                returning="result")
        public void afterReturning(JoinPoint jp, Object result) {
            log.info("调用" + jp.getTarget() + "的" + 
                    jp.getSignature() + "方法,方法返回值" +
                    result);
        }
    }
    

    三、使用注解丁义珍增强

    需求说明:使用注解来定义异常抛出增强
    分析:

    • 使用@AfterThrowing注解定义异常抛出增强

    增强类:

    package aop;
    
    import org.apache.log4j.Logger;
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.annotation.AfterThrowing;
    import org.aspectj.lang.annotation.Aspect;
    
    /**
     * 定义包含增强方法的JavaBean
     */
    @Aspect
    public class ErrorLogger {
        private static final Logger log = Logger.getLogger(ErrorLogger.class);
    
        @AfterThrowing(pointcut="execution(* service.UserService.*(..))",
                throwing="e")
        public void afterThrowing(JoinPoint jp, RuntimeException e) {
            log.error(jp.getSignature().getName() + " 方法发生异常:" + e);
        }
    }
    

    dao层

    package dao.impl;
    
    import org.springframework.stereotype.Repository;
    
    import dao.UserDao;
    import entity.User;
    
    /**
     * 用户DAO类,实现UserDao接口,负责User类的持久化操作
     */
    @Repository("userDao")
    public class UserDaoImpl implements UserDao {
    
        public void save(User user) {
            // 这里并未实现完整的数据库操作,仅为说明问题
            System.out.println("保存用户信息到数据库");
            throw new RuntimeException("为测试程序运行效果抛出的异常");
        }
    }
    

    配置文件:

    <?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-3.2.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
        <!-- 扫描包中注解标注的类 -->
        <context:component-scan base-package="service,dao" />
        <bean class="aop.ErrorLogger"></bean>
        <!--  启动对Spring AOP的AspectJ注解的支持  -->
        <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
    </beans>
    

    运行结果:


    image.png

    四、使用注解定义最终增强

    需求:使用注解来定义最终增强
    分析:使用@After注解定义最终增强
    增强类:

    package aop;
    
    import org.apache.log4j.Logger;
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.annotation.After;
    import org.aspectj.lang.annotation.Aspect;
    
    @Aspect
    public class AfterLogger {
        
        private static Logger log = Logger.getLogger(AfterLogger.class);
        
        @After("execution(* service.UserService.*(..))")
        public void after(JoinPoint jp) {
            log.info(jp.getSignature().getName() + "方法结束了");
        }
    
    }
    

    配置文件:

    <?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-3.2.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
        <!-- 扫描包中注解标注的类 -->
        <context:component-scan base-package="service,dao" />
        <bean class="aop.AfterLogger"></bean>
        <!--  启动对Spring AOP的AspectJ注解的支持  -->
        <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
    </beans>
    

    运行结果:


    image.png

    五、使用注解定义环绕增强

    需求说明:使用注解来定义环绕增强
    分析:使用@Around注解定义环绕增强
    增强类:

    package aop;
    
    import java.util.Arrays;
    
    import org.apache.log4j.Logger;
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.annotation.Around;
    import org.aspectj.lang.annotation.Aspect;
    
    @Aspect
    public class AroundLogger {
        
        private static Logger log = Logger.getLogger(AroundLogger.class);
        
        /**
         * 可以通过修改这个方法的返回值来修改目标方法的返回值
         * @param jp
         * @return
         * @throws Throwable 
         */
        @Around("execution(* service.UserService.*(..))")
        public Object aroundLogger(ProceedingJoinPoint jp ) throws Throwable {
            log.info("调用" + jp.getTarget() + "的" + 
                    jp.getSignature() + "方法,方法参数" +
                    Arrays.toString(jp.getArgs()));
            Object result;
            try {
                result = jp.proceed();
                log.info("调用" + jp.getTarget() + "的" + 
                        jp.getSignature() + "方法,方法返回值" +
                        result);
                return result;
            } catch (Throwable e) {
                log.error(jp.getSignature().getName() + " 方法发生异常:" + e);
                throw e;
            }finally {
                log.info(jp.getSignature().getName() + " 方法结束执行。");
            }
        }
        
    }
    

    配置文件:

    <?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-3.2.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
        <!-- 扫描包中注解标注的类 -->
        <context:component-scan base-package="service,dao" />
        <bean class="aop.AroundLogger"></bean>
        <!--  启动对Spring AOP的AspectJ注解的支持  -->
        <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
    </beans>
    

    运行结果:


    image.png

    六、小结

    image.png
    image.png

    相关文章

      网友评论

          本文标题:十、使用注解定义切面

          本文链接:https://www.haomeiwen.com/subject/ojhrwftx.html