zoukankan      html  css  js  c++  java
  • java之Spring实现AOP

    方式一,实现MethodBeforeAdvice,AfterReturningAdvice接口,在applicationContext.xml中注入bean,创建切入点,配置环绕增加,xml需要引入aop约束。
    public void before(Method method, Object[] objects, Object o)//目标方法,方法参数,目标类
    public void afterReturning(Object o, Method method, Object[] objects, Object o1)//目标方法返回值,目标方法,方法参数,目标类

    <aop:config>
            <!-- 切入点 execution(返回类型 类.方法名(参数列表))-->
            <!--第一个*代表所有类型,第二个*代表类中所有方法,(..)代表任意参数-->
            <aop:pointcut id="pointcut" expression="execution(* com.jay.service.UserServiceImpl.*(..))"/>
            <!--执行环绕增加-->
            <aop:advisor advice-ref="logBefore" pointcut-ref="pointcut"></aop:advisor>
            <aop:advisor advice-ref="logAfter" pointcut-ref="pointcut"></aop:advisor>
    </aop:config>
    

     方式二,自定义类和方法,方法中无法通过参数自动获取目标类的相关信息

    <aop:config>
        <aop:aspect ref="log">
            <aop:pointcut id="point" expression="execution(* com.jay.service.UserService.*(..))"/>
            <aop:before method="before" pointcut-ref="point" />
            <aop:after method="after" pointcut-ref="point" />
        </aop:aspect>
    </aop:config>
    

     方式三,注解实现AOP

    package com.jay.service;
    
    import org.aspectj.lang.annotation.After;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Before;
    
    @Aspect
    public class AnnotationPointCut {
        @Before("execution(* com.jay.service.UserServiceImpl.*(..))")
        public void before(){
            System.out.println("前...");
        }
        @After("execution(* com.jay.service.UserServiceImpl.*(..))")
        public void after(){
            System.out.println("后...");
        }
    }
    

     配置:

    <!--方式三,注解实现AOP-->
    <bean id="annotationPointCut" class="com.jay.service.AnnotationPointCut"/>
    <!--开启注解支持-->
    <aop:aspectj-autoproxy/>
    

     测试:

    @Test
    public void test3() {
            ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            //代理的是一类业务,需要使用接口
            UserService m = context.getBean("userService",UserService.class);
            m.getUser("jay.x");
    }
    

     要引入依赖
    <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
    <dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.7</version>
    </dependency>

  • 相关阅读:
    iOS--推送
    iOS 多线程之GCD
    iOS多线程之NSThread
    NSUserDefaults的简单使用
    stat命令的实现-mystat
    linux pwd指令的C实现
    2019-2020-1 20175307 20175308 20175319 实验五 通讯协议设计
    2019-2020-1 20175307 20175308 20175319 实验四 外设驱动程序设计
    2019-2020-1 20175307 20175308 20175319 实验三 并发程序
    2019-2020-1 20175307 20175308 20175319 实验二 固件程序设计
  • 原文地址:https://www.cnblogs.com/xsj1989/p/15078841.html
Copyright © 2011-2022 走看看