spring增强方式常用的两种,@Around示例

引入spring的几个jar包到工程
在src下建立包AspectTest;
然后在包下创建以下类。

service接口跟实现

package AspectTest;  

import entiry.Person;

/** 
 * <a href="http://www.itsoku.com" style="font-weight:bold;" target="_blank">我的技术网站</a> 2016/11/15 0015. 
 */  
public interface IAService {  
    String m1(Person p3);  
    void m2(); 
     String m3(Person p1,Person p)  ;
}  
package AspectTest;

import org.springframework.stereotype.Component;  


import entiry.Person;

import javax.annotation.Resource;  

/** 
 * <a href="http://www.itsoku.com" style="font-weight:bold;" target="_blank">我的技术网站</a> 2016/11/15 0015. 
 */  
@Component("aservice")  
public class AServiceImpl implements IAService {  
//自定义注解Servicelock在m1上
  @Servicelock
    public String m1(Person p3)  
    {  
        System.out.println(AServiceImpl.class+".m1()");  
        return AServiceImpl.class+".m1()+=================================";  
    }  

    @Override  
    public void m2() {  
        int i=0;  
        System.out.println(10/i);  
    }  

    public String m3(Person p1,Person p)  
    {  
        System.out.println(AServiceImpl.class+".m1()");  
        return AServiceImpl.class+".m1()+=================================";  
    }


}  

方式1,直接写增强切面类

package AspectTest;  

import org.aspectj.lang.ProceedingJoinPoint;  
import org.aspectj.lang.annotation.Around;  
import org.aspectj.lang.annotation.Aspect;  
import org.springframework.core.annotation.Order;  
import org.springframework.stereotype.Component;  

/** 
 * <a href="http://www.itsoku.com" style="font-weight:bold;" target="_blank">我的技术网站</a> 2016/11/17 0017. 
 */  
@Component  
@Aspect  
//@Order(1000001)  
public class Around2 { 
    @Around(value = "execution(* AspectTest.*Impl.*(..))") 
    //AServiceImpl 环绕增强AServiceImpl 所有方法
    public Object exec(ProceedingJoinPoint invocation) throws Throwable {  
        System.out.println("Around2");
        Order order = this.getClass().getAnnotation(Order.class);  
        if(order!=null)  System.out.println(Around2.class+" Around通知 order = "+order.value()+" start");  
        Object result = invocation.proceed();  
        if(order!=null)  System.out.println(Around2.class+" Around通知 order = "+order.value()+" end"); 
        System.out.println("Around2----end");
        return result;  
    }  
}  


第二种通过自定义注解
注解类

package AspectTest;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(value={ElementType.PARAMETER, ElementType.METHOD})
@Retention(value=RetentionPolicy.RUNTIME)
@Documented

public  @interface Servicelock { 
     String description()  default "";
}

切面类

package AspectTest;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Scope;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
//单利多利
@Scope
@Aspect
@Order(100)
public class LockAspect {
    /**
     * 思考:为什么不用synchronized
     * service 默认是单例的,并发下lock只有一个实例
     */
    private static  Lock lock = new ReentrantLock(true);//互斥锁 参数默认false,不公平锁  

    //Service层切点     用于记录错误日志
    @Pointcut("@annotation(AspectTest.Servicelock)")  
    public void lockAspect() {

    }

    @Before("lockAspect()")
    public void exec(){ 


        Object obj = null;
        System.out.println("before1+lockAspect");

    } 
    @Around("lockAspect()")
    public  Object around(ProceedingJoinPoint joinPoint) { 
        lock.lock();
      System.out.println(  "locked/...............");
        Object obj = null;
        try {
            obj = joinPoint.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
        } finally{
            lock.unlock();
            System.out.println(  "unununulocked/...............");
        }
        return obj;
    } 


   @After(value = "lockAspect()")  
   public void exec1(){  
    System.out.println("after+lockAspect");
       Order order = this.getClass().getAnnotation(Order.class);  
       if(order!=null)  System.out.println(After2.class+" After通知 order = "+order.value());  
   } 
}

测试类

package AspectTest;  

import java.util.Date;

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

import entiry.Person;

/** 
 * <a href="http://www.itsoku.com" style="font-weight:bold;" target="_blank">我的技术网站</a> 2016/11/17 0017. 
 */  
public class Client {  
    public static void main(String[] args) {  
        //BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:/AspectTest/spring-demo4.xml");  
        IAService aservice = context.getBean("aservice", IAService.class);  
        System.out.println("\n========================\n");  
       aservice.m1(new Person(1, "WHJ", 12, "Ss", new Date()));  

        System.out.println("\n========================\n");  
        try {  
         //   aservice.m2();  
        } catch (Exception e){  
            //暂时不输出错误信息  
            System.out.println("sssss");
            e.printStackTrace();
        }  
    }  
}  

简单xml配置

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
       xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"  
       xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"  
       xmlns:p="http://www.springframework.org/schema/p"  
       xsi:schemaLocation="http://www.springframework.org/schema/beans  
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context-3.1.xsd   
    http://www.springframework.org/schema/aop   
    http://www.springframework.org/schema/aop/spring-aop-3.1.xsd   
    http://www.springframework.org/schema/tx    
    http://www.springframework.org/schema/tx/spring-tx-3.1.xsd" default-autowire="byName">  
    <aop:aspectj-autoproxy />  
    <context:component-scan base-package="AspectTest"/>  

    <!-- 如果目标对象实现了接口 默认情况下会使用动态代理实现AOP,也可以强制使用CGLIB
1)加入 CGLIB库
2)在配置文件中加入<aop:aspectj-autoproxy proxy-target-class="true"/> -->
</beans>  
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
@Around是Spring AOP的一个注解,用于实现面向切面编程。它可以在目标方法之前和之后织入增强动作,并且可以决定目标方法的执行时机、执行方式,甚至可以完全阻止目标方法的执行。此外,@Around还可以改变目标方法的参数值和返回值。 下面是一个@Around使用示例: ```java @Aspect @Component public class LoggingAspect { @Around("execution(* com.example.MyService.*(..))") public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable { long startTime = System.currentTimeMillis(); Object result = joinPoint.proceed(); long endTime = System.currentTimeMillis(); long executionTime = endTime - startTime; System.out.println(joinPoint.getSignature() + " executed in " + executionTime + "ms"); return result; } } ``` 在上面的示例,我们定义了一个切面类LoggingAspect,并在其定义了一个@Around增强方法logExecutionTime。该方法使用了@Around注解,并指定了切入点表达式execution(* com.example.MyService.*(..)),表示对com.example.MyService包下的所有方法进行增强。 在logExecutionTime方法,我们首先记录了目标方法的开始时间startTime,然后调用joinPoint.proceed()执行目标方法,并将返回值保存在result变量。接着,我们计算了目标方法的执行时间executionTime,并打印了执行时间信息。最后,我们返回了目标方法的返回值result。 通过使用@Around注解,我们可以在目标方法执行前后进行一些额外的操作,比如记录方法的执行时间、打印日志等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值