使用注解(基于Aspect)

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

    
    
    

@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("后置");
    }
}

你可能感兴趣的:(使用注解(基于Aspect))