使用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);
}
}