Spring AOP--通过反射访问存储库自动生成的字段 [英] Spring AOP - Access to Repositories autowired field by reflection

查看:49
本文介绍了Spring AOP--通过反射访问存储库自动生成的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是第一次在AspectJ中,我可能需要访问存储库的本地私有自动连接字段,以便准确地在该实例上执行某些操作。

我创建了一个切入点,重点放在每个@Repository注释类的每个方法上。当切入点触发时,我获取要从中获取bean字段的当前类实例。

这是办法:

@Repository
public class MyDao {

    @Autowired
    private MyBean bean;

    public List<Label> getSomething() {
        // does something...
    }
}


@Aspect
@Component
public class MyAspect {

    @Pointcut("within(@org.springframework.stereotype.Repository *)")
    public void repositories() {
    }

    @Before("repositories()")
    public void setDatabase(JoinPoint joinPoint) {
        try {
            Field field = ReflectionUtils.findField(joinPoint.getThis().getClass(), "bean"); // OK since here - joinPoint.getThis().getClass() -> MyDao
            ReflectionUtils.makeAccessible(field); // Still OK
            Object fieldValue = ReflectionUtils.getField(field, joinPoint.getThis());
            System.out.println(fieldValue == null); // true

            // should do some stuff with the "fieldValue"
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

fieldValue始终为null,即使我改为创建类似private | public | package String something = "blablabla";的内容。

我已确保在应用程序启动时实际实例化了"Bean"(使用调试器进行了验证)。

我关注了How to read the value of a private field from a different class in Java?

我错过了什么?|有可能吗?|有没有其他方法?

推荐答案

@springbootlearner建议使用此方法access class variable in aspect class

我所要做的就是将joinPoint.getThis()替换为joinPoint.getTarget()

最终解决方案是:

@Aspect
@Component
public class MyAspect {

    /**
     *
     */
    @Pointcut("within(@org.springframework.stereotype.Repository *)")
    public void repositories() {
    }

    /**
     * @param joinPoint
     */
    @Before("repositories()")
    public void setDatabase(JoinPoint joinPoint) {
       Object target = joinPoint.getTarget();

       // find the "MyBean" field
       Field myBeanField = Arrays.stream(target.getClass().getDeclaredFields())
            .filter(predicate -> predicate.getType().equals(MyBean.class)).findFirst().orElseGet(null);

       if (myBeanField != null) {
           myBeanField.setAccessible(true);
           try {
              MyBean bean = (MyBean) myBeanField.get(target);// do stuff
           } catch (IllegalAccessException e) {
               e.printStackTrace();
           }
       }
    }

}

这篇关于Spring AOP--通过反射访问存储库自动生成的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆