不废话,上代码(简化到了极致)
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 对象,它也是直接的实现类,它的类型不应该是一个代理类型的吗?