Spring AOP报错 ensure that AopContext.currentProxy() is invoked in the same thread

使用AopContext.currentProxy()时报错了.如下

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.

同一个类中调用

1.在启动类上加上

@EnableAspectJAutoProxy(exposeProxy = true)来暴露AOP的Proxy对象才行,否则会报异常

@EnableAspectJAutoProxy(exposeProxy = true)
Cannot find current proxy: Set 'exposeProxy' property on Advised to 'true' to make it available.

注意:exposeProxy = true 是用来暴露AOP的Proxy对象的
产生代理对象就必须要产生一个切面,如果没有,创建代理对象的时候我们会发现对象中的exposeProxy属性还是false,不管你是否设置了exposeProxy = true。
2.调用处写

((YourClass) AopContext.currentProxy()).YourMethid(参数);

不同类中调用

写一个工具类获取Spring 的bean,然后通过 SpringUtil去获取类,然后调用你的方法

@Component
public class SpringUtil implements ApplicationContextAware {
	
	private static ApplicationContext applicationContext;
 
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		if(SpringUtil.applicationContext == null) {
            SpringUtil.applicationContext = applicationContext;
        }
	}
 
	 //获取applicationContext
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
 
    //通过name获取 Bean.
    public static Object getBean(String name){
        try {
            return getApplicationContext().getBean(name);
        }catch (NoSuchBeanDefinitionException e){
            //获取不到时返回null
            return null;
        }
    }
 
    //通过class获取Bean.
    public static <T> T getBean(Class<T> clazz){
        return getApplicationContext().getBean(clazz);
    }
 
    //通过name,以及Clazz返回指定的Bean
    public static <T> T getBean(String name,Class<T> clazz){
        return getApplicationContext().getBean(name, clazz);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值