https://www.cnblogs.com/yjmyzz/p/why-spring-aop-does-not-work.html
具体原因就是AOP的实现有二类,如果是基于接口的,会采用动态代理,生成一个代理类,如果是基于类的,会采用CGLib生成子类,然后在子类中扩展父类中的方法。
而普通的类并不是接口,所以aop并没起作用。
解决方法:
(1)通过注解将该类进行注入,然后在调用处使用注入的类
(1)首先是自定义注解
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface WatcherInterface {
/**
* 功能描述
*/
String description() default "";
/**
* 接受信息的手机号,中间用|隔开
*/
String phone() default "18539270747|13610438456";
}
(2)定义切面
@Aspect
@Component
@Slf4j
public class WatcherAdvice {
@Pointcut("xxx.WatcherInterface")
private void watchInter() {
}
}
(3)给需要用的地方加上注解,这里我注解打在了普通的方法上,因此需要将该类交由spring管理
@Slf4j
@Component
public class ExternalDataInterface {
/**
* 功能描述 通过车牌号获取保单信息
*
* @param licenseNo 车牌号
* @param specifiedTime 报案日期
* @date 2020/9/14 14:17
*/
@WatcherInterface(description = "通过车牌号和报案日期获取保单信息")
public List<LocalIds> getPolicyInfoForMy(String licenseNo,String specifiedTime){
//具体内容省略。。。。
}
}
(4)在用的地方必须通过注解注入进来 ,此处我是在controller层调用的,因此代码是下面的
@RequestMapping("/external")
@RestController
@Slf4j
public class ExternalInterfaceController extends BaseController {
@Resource
private ExternalDataInterface externalDataInterface;
@PostMapping("listReportCaseInfos")
public Map listReportCaseInfos() {
return responseOk(externalDataInterface.getPolicyInfoForMy('A','B'), "获取数据成功");
}
}
(2)通过ApplicationContext.getBean()获取制定注解的类,原理与上面相同
(3)利用AopContext
XXClass xx = (XXclass)AopContext.currentProxy();
不过这个方法要注意的是,主类入口上,必须加上exporseProxy=true,参考下图:
@SpringBootApplication(scanBasePackages = "cn.com.xx.pv.**")
@MapperScan("cn.com.xx.pv.mapper")
@EnableTransactionManagement
@EnableAspectJAutoProxy(exposeProxy = true)
public class PvApplication {
public static void main(String[] args) {
ApplicationContextManager.setApplicationContext(SpringApplication.run(PvApplication.class, args));
}
}