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 对象,它也是直接的实现类,它的类型不应该是一个代理类型的吗?

@EnableAspectJAutoProxy 只是能让你自己代理自己,
AopContext.currentProxy() 出来的对象是ThreadLocal中保存的一个自己的代理对象,如果自己本身没有被代理,那么就是获取到的就是null的

img

在实现类的方法上加个 @Transactional 等类似的注解,让实现类被代理应该就可以了