地推 2022-10-27 10:27 采纳率: 58.8%
浏览 39
已结题

springboot 中 @EnableAspectJAutoProxy 不起作用

不废话,上代码(简化到了极致)

1、Service接口

package com.example.springboot1.service;

public interface ICalculator {
int calculate(int a, int b);
}
2、Service 实现

package com.example.springboot1.service;

import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;

@Service
public class CalculatorImpl implements ICalculator{
@Override
public int calculate(int a, int b) {
try{
System.out.println(AopContext.currentProxy().getClass().getName());
}catch (Exception ex){
ex.printStackTrace();
}
return a + b;
}
}
3、Controller

package com.example.springboot1.ctrl;

import com.example.springboot1.service.ICalculator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController("/test/")
public class Root {

@Autowired
private ICalculator calculator;

@RequestMapping("/calculate")
public String calculate() {
    calculator.calculate(1, 2);
    return calculator.getClass().getName();
}

}
4、启动类

复制代码
package com.example.springboot1;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true)
@SpringBootApplication
public class SpringBoot1Application {

public static void main(String[] args) {
    SpringApplication.run(SpringBoot1Application.class, args);
}

}
复制代码

访问 http://localhost:8080/calculate 后,控制台出现异常:

java.lang.IllegalStateException: Cannot find current proxy: Set 'exposeProxy' property on Advised to 'true' to make it available, and ensure that AopContext.currentProxy() is invoked in the same thread as the AOP invocation context.
at org.springframework.aop.framework.AopContext.currentProxy(AopContext.java:69)
at com.example.springboot1.service.CalculatorImpl.calculate(CalculatorImpl.java:11)
浏览器得到的内容是:

com.example.springboot1.service.CalculatorImpl

不但在 Service实现类中 AopContext.currentProxy() 不能调用,而且 注入到 controller 中的 service 对象,它也是直接的实现类,它的类型不应该是一个代理类型的吗?

  • 写回答

2条回答 默认 最新

  • CSDN-Ada助手 CSDN-AI 官方账号 2022-10-27 12:12
    关注
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 10月27日
  • 已采纳回答 10月27日
  • 创建了问题 10月27日

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料