使用注解(基于Aspect)

Spring不会自动寻找注解,必须告诉Spring哪些包中可能有注解
在applicationContext.xml内配置如下即可:(需要引入xmlns:context)

    <context:component-scan base-package="com.Demo,com.advice"/>
    <!--true表示使用cglib动态代理,false表示使用jdk动态代理,注解都是使用cglib做的-->
    <aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>

@Component注解相当于bean标签,id默认为类名首字母小写,也可以直接设置id

package com;

import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Component("demo")
public class Demo {
    @Pointcut("execution(* com.Demo.demo1())")
    public void demo1() {
        System.out.println("demo1");
    }

    public void demo2() throws Exception {
        int i = 1 / 0;
        System.out.println("demo2");
    }

    public void demo3() {
        System.out.println("demo3");
    }
}

通知类:

package com.advice;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class AfterAdvice {
    @After("com.Demo.demo1()")
    public void after(){
        System.out.println("后置");
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本来是准备看一看Spring源码的。然后在知乎上看到来一个帖子,说有一群**自己连Spring官方文档都没有完全读...
    此鱼不得水阅读 11,822评论 4 21
  • 深入使用 Spring两种后处理器Bean 后处理器容器后处理器属性占位符配置器重写占位符配置器Spring 的自...
    渐丶忘阅读 4,785评论 0 1
  • 转 Spring****基于 Annotation 的简单介绍 2011年03月29日 15:07:00 阅读数:...
    fd649cf896c0阅读 2,720评论 1 0
  • Spring致力于提供一种方法管理你的业务对象。在大量Java EE的应用中,随处可见Spring。今天我将简单的...
    JAVA架构师的圈子阅读 5,180评论 0 16
  • Spring入门使用Spring容器Spring容器使用ApplicationContextApplication...
    渐丶忘阅读 5,247评论 0 4