美文网首页
Spring Aop注解使用

Spring Aop注解使用

作者: torres1 | 来源:发表于2019-12-17 15:55 被阅读0次

    前言

    本文简介spring aop注解的使用方式

    1.创建实体类

    @Data
    public class Peach {
        private String name;
        private int price;
    
        public void grow() {
            System.out.println("peach grow...");
        }
    }
    

    2.创建切面

    @Aspect
    public class PeachAspect {
    
        /**
         * 定义切点
         */
        @Pointcut("execution(* com.cqliu.aop.Peach.grow(..))")
        private void execute() {}
    
        @Before("execute()")
        private void before(JoinPoint joinPoint) {
            System.out.println("Peach before...");
        }
    
        @After("execute()")
        private void after(JoinPoint joinPoint) {
            System.out.println("Peach after...");
        }
    
        @AfterReturning("execute()")
        private void afterReturn(JoinPoint joinPoint) {
            System.out.println("Peach afterReturn...");
        }
    
        @AfterThrowing("execute()")
        private void afterThrow(JoinPoint joinPoint) {
            System.out.println("Peach afterThrow..");
        }
    
        @Around("execute()")
        private void around(ProceedingJoinPoint point) throws Throwable {
            System.out.println("Peach around_start");
            point.proceed();
            System.out.println("Peach around_end");
        }
    }
    

    3.配置文件

    <?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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
        <aop:aspectj-autoproxy/>
        <bean id="peach" class="com.cqliu.aop.Peach"/>
        <bean id="peachAspect" class="com.cqliu.aop.PeachAspect"/>
    </beans>
    

    输出

        public static void main(String[] args) {
            ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("aop-beans.xml");
            Peach peach = (Peach) applicationContext.getBean("peach");
            peach.grow();
        }
    
    Peach around_start
    Peach before...
    peach grow...
    Peach around_end
    Peach after...
    Peach afterReturn...
    

    相关文章

      网友评论

          本文标题:Spring Aop注解使用

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