这篇文章主要介绍了Spring5之动态AOP的使用案例,通过一个案例来了解AOP的使用方式,需要的朋友可以参考一下。
1、创建用于拦截的bean
在实际工作中,此bean可能是满足业务需要的核心逻辑,例如test方法可能会封装着某个核心业务。但是,如果完美想在test前后加入日志来跟踪调试。如果直接修改源码并不符合面向对象的设计方法,而且随着改动原有代码也有一定的风险,还好接下来的Spring帮我们做到了这一点。
package com.test.spring5code.bean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
* @Description: MyTestBean
* @Author: Janson
* @Date: 2020/4/25 12:26
**/
@Slf4j
@Component
public class MyTestBean {
private String testStr;
public String getTestStr() {
return testStr;
}
public void setTestStr(String testStr) {
this.testStr = testStr;
}
public void test() {
log.info("test");
}
}
2、创建通知Advisor
Spring中摒弃了最原始的繁杂配置方式而采用@Aspect注解对POJO进行标注,使AOP的工作大大简化,例如在MyAspectJ类中,我们要做的就是在所有类的test方法执行前在控制台打印beforeTest,而在所有类的test方法执行后打印afterTest,同时又使用环绕的方式在所有类的方法执行前后再次分别打印before1和after1。
package com.test.spring5code.aspect;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
* @Description: aspect test
* @Author: Janson
* @Date: 2020/4/20 22:13
**/
@Aspect
@Slf4j
@Component
public class MyAspectJ {
@Pointcut("execution(* com.test.spring5code.bean.*.*(..))")
public void test() {
}
@Before("test()")
public void beforeTest() {
log.info("beforeTest");
}
@After("test()")
public void after() {
log.info("afterTest");
}
@Around("test()")
public Object aroundTest(ProceedingJoinPoint proceedingJoinPoint) {
log.info("before1");
Object o = null;
try {
o = proceedingJoinPoint.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
log.info("after1");
return o;
}
}
3、创建配置类
package com.test.spring5code.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* @Description: 配置类
* @Author: Janson
* @Date: 2020/4/25 11:37
**/
@Configuration
@ComponentScan(basePackages = "com.test.spring5code")
public class BeansConfig {
}
4、测试类
package com.test.spring5code;
import com.test.spring5code.bean.MyTestBean;
import com.test.spring5code.config.BeansConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* @Description: MyAspectJ Test
* @Author: Janson
* @Date: 2020/4/20 22:46
**/
public class MyAspectJTest {
public static void main(String[] args) {
AnnotationConfigApplicationContext configApplicationContext = new AnnotationConfigApplicationContext(BeansConfig.class);
MyTestBean myTestBean = configApplicationContext.getBean(MyTestBean.class);
myTestBean.test();
}
}
5、测试类输出结果
可以看到在我们输出test前后分别打印出我们之前定义的日志内容,实现了在方法前后打印日志。
15:39:42.566 [main] INFO com.test.spring5code.aspect.MyAspectJ - before1
15:39:46.379 [main] INFO com.test.spring5code.aspect.MyAspectJ - beforeTest
15:39:46.443 [main] INFO com.test.spring5code.bean.MyTestBean - test
15:40:20.782 [main] INFO com.test.spring5code.aspect.MyAspectJ - after1
15:40:32.049 [main] INFO com.test.spring5code.aspect.MyAspectJ - afterTest
如果您觉得有帮助,欢迎点赞哦 ~ ~ 多谢~ ~