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