springboot aop切到service层,不生效
发现一个问题
使用aop切到service层方法上,idea会有切成功的标志,编译也不报错,但就是不生效。
研究了下发现,是因为我切的方法被同一个service中的其他方法调用,这样的话就不生效了,原因是切面只能对被spring代理的对象起作用,自己调用不行,解决方法是切到spring代理的方法上,这只是切点不生效的一种情况,给到大家参考。
aop文件:
//注释掉的是原来不生效的方式 //@afterreturning("execution( * cn.qdcares.fodmonitor.web.api.fodmonitor.fodtask.service.impl.fodtaskserviceimpl.radarsubmitfodtask(..))") @afterreturning("execution( * cn.qdcares.fodmonitor.web.api.fodmonitor.fodtask.service.impl.fodtaskserviceimpl.refreshradarfodtask(..))") public void createfodafterreturning(joinpoint joinpoint){
service文件二者关系:
//切到这里生效 @override public int refreshradarfodtask(radarfod radarfod) { //判断数据库中是否存在数据 //从而进行新增或更新操作 optional<fodtask> optional = fodtaskrepository.findbyfodid(radarfod.getid()); if (optional.ispresent()){ updatefodtaskbyfodid(radarfod); return 1; } radarsubmitfodtask(radarfod); return 1; } //切到这里不生效 @override public int radarsubmitfodtask(radarfod radarfod) { return 1; }
spring中aop无法拦截service层内部方法调用
问题描述
在service类中有个a方法调用内部b方法时,无法拦截到b方法。
示例:
例如如下示例代码,当访问controller的hello方法时,无法拦截service层testa方法中调用到的内部testb方法。
package com.example.test.controller; import com.example.test.service.service; ================================================controller层======== @restcontroller public class testcontroller{ @autowired service service; @requestmapping("") public void hello(string name) { service.testa(name); } } ================================================service层======== package com.example.test.service; public class service{ public void testa(string name); } ================================================service实现类======== package com.example.test.service.impl; public class serviceimpl impl service{ @override @transactional public void testa(string name) { testb(name); } public void testb(string name){ } } ==========================aspect============= @component @aspect @order(1) public class serviceaspect { @before("execution(* com.example.test..*.testa(..))") public void approve(joinpoint joinpoint) { object[] args = joinpoint.getargs(); } }
解决方法
1.修改service层的testa方法:
package com.example.test.service.impl; public class serviceimpl impl service{ @override @transactional public void testa(string name) { serviceimpl service = aopcontext.currentproxy() != null ? (serviceimpl)aopcontext.currentproxy() : this; service.testb(name); } public void testb(string name){ system.out.println(name); } }
2.在springboot启动类上开启aop代理
@enableaspectjautoproxy(exposeproxy = true)
3.重新启动后,aop就能拦截到testb方法。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论