Aop温故


AspectJ使用org.aspectj.lang.JoinPoint接口表示目标类连接点对象,如果是环绕增强时,使用org.aspectj.lang.ProceedingJoinPoint表示连接点对象,该类是JoinPoint的子接口。任何一个增强方法都可以通过将第一个入参声明为JoinPoint访问到连接点上下文的信息。我们先来了解一下这两个接口的主要方法: 
1)JoinPoint 
java.lang.Object[] getArgs():获取连接点方法运行时的入参列表; 
Signature getSignature() :获取连接点的方法签名对象; 
java.lang.Object getTarget() :获取连接点所在的目标对象; 
java.lang.Object getThis() :获取代理对象本身; /**
* 声明一个注解 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Action { String name(); }
@Service
public class DemoAnnotationService {
    @Action(name="注解式拦截的add操作")
    public void add(){

    }
}
 
@Service
public class DemoMethodService {
    public void add(){}
}

@Aspect
@Component //配置为bean
public class LogAspect {
    @Pointcut("@annotation(com.wisely.aop.Action)")//申明一个切面,供重复使用
    public void annotationPointCut(){}

    /**
     * joinPoint主要用于和被代理类交互,前面对该类有解释说明
     * @param joinPoint
     */
    @After("annotationPointCut()")
    public void after(JoinPoint joinPoint){
        MethodSignature signature=(MethodSignature)joinPoint.getSignature();
        Method method=signature.getMethod();
        Action action=method.getAnnotation(Action.class);
        System.out.println("注解式拦截 "+action.name());
    }
    @Before("execution(* com.wisely.aop.DemoMethodService.*(..))")
    public void before(JoinPoint joinPoint){
        MethodSignature signature=(MethodSignature)joinPoint.getSignature();
        Method method=signature.getMethod();
        System.out.println("方法规则式拦截,"+method.getName());
    }
}

@Configuration//该类为配置类
@ComponentScan("com.wisely.aop")//扫描包下所有使用@Service,@Component,@Repository,@Controller的类并注册为bean
@EnableAspectJAutoProxy //该注解用于开启Spring对AspectJ的支持
public class AopConfig {
}


public class Main {
    public static void main(String[] args){
        AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext(AopConfig.class);
        DemoAnnotationService demoAnnotationService=context.getBean(DemoAnnotationService.class);
        DemoMethodService demoMethodService=context.getBean(DemoMethodService.class);
        demoAnnotationService.add();
        demoMethodService.add();
        context.close();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值