对某个类型中的方法进行拦截,然后加入固定的业务逻辑,这是AOP面向切面编程可以做的事,在springboot里实现aop的方法也有很多, spring-boot-starter-aop
或者 aspectjweaver
都是可以实现的,不过我们在实现之前,先来看一下aop里的几个概念。
概念
实现
1 引用依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2 添加切面和拦截的行为
@Aspect
@Component
@Slf4j
public class TestAspect {
/**
* 对TestService类下面的所有方法拦截.
*/
@Pointcut("execution(* com.lind.start.test.aop.TestService.*(..))")
public void pointcut() {
}
//前置通知
@Before("pointcut()")
public void beforeMethod(JoinPoint joinPoint) {
if (joinPoint.getArgs().length == 1 && joinPoint.getArgs()[0] instanceof User) {
User user = (User) joinPoint.getArgs()[0];
user.setUsername("aop赋值");
log.info("调用了前置通知" + user.toString());
}
}
//@After: 后置通知
@After("pointcut()")
public void afterMethod(JoinPoint joinPoint) {
log.info("调用了后置通知");
}
//@AfterRunning: 返回通知 result为返回内容
@AfterReturning(value = "pointcut()", returning = "result")
public void afterReturningMethod(JoinPoint joinPoint, Object result) {
log.info("调用了返回通知");
}
//@Around:环绕通知
@Around("pointcut()")
public Object Around(ProceedingJoinPoint pjp) throws Throwable {
log.info("around执行方法之前");
Object object = pjp.proceed();
log.info("around执行方法之后--返回值:" + object);
return object;
}
}
3 调用及结果
@SpringBootTest
@RunWith(SpringRunner.class)
public class AopTest {
@Autowired
TestService testService;
@Test
public void test() {
testService.print(new User());
}
}
总结
到此这篇关于springboot 使用自定义的aspect的示例代码的文章就介绍到这了,更多相关springboot自定义的aspect内容请搜索亿速云以前的文章或继续浏览下面的相关文章希望大家以后多多支持亿速云!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。