1.编写aop配置类,配置类上加入EnableAspectJAutoProxy注解。
@EnableAspectJAutoProxy
@Configuration
public class MainConfigOfAop {
//业务类
@Bean
public TestBean testBean(){
return new TestBean();
}
//切面类
@Bean
public AspectJTest aspectJTest(){
return new AspectJTest();
}
}
2.编写通知类,标注Aspect注解,切点表达式,还有前置通知,后置通知,环绕通知等
@Aspect
public class AspectJTest1 {
@Pointcut("execution(* *.test(..))")
public void test(){
}
@Before("test()")
public void beforeTest(){
System.out.println("beforeTest1");
}
@After("test()")
public void afterTest(){
System.out.println("afterTest1");
}
@Around("test()")
public Object arountTest(ProceedingJoinPoint p){
System.out.println("before11");
Object o = null;
try {
o = p.proceed();
} catch (Throwable e) {
e.printStackTrace();
}
System.out.println("after11");
return o;
}
}
3.测试类编写
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(MainConfigOfAop.class);
TestBean testBean = ac.getBean(TestBean.class);
testBean.test();
}
}