-1

It's for the first time that Inside an AspectJ I may need to access a local private autowired field of a Repository in order to do some stuff on >exactly< that instance.

I created a pointcut that focuses on each method of every @Repository annotated class. When the pointcut fires, I get the current class instance from which I want to get the bean field.

This is the way:

@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 is always null even if I create something like private | public | package String something = "blablabla"; instead.

I have ensured that "bean" is actually instantiated when the application starts (verified with the debugger).

I followed How to read the value of a private field from a different class in Java?

What I am missing? | Is it possible? | Are there any different ways?

Andrea Grimandi
  • 631
  • 2
  • 8
  • 32

1 Answers1

0

@springbootlearner suggested this approach access class variable in aspect class

All I had to do is to replace the joinPoint.getThis() with joinPoint.getTarget()

And the final solution is:

@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();
           }
       }
    }

}
Andrea Grimandi
  • 631
  • 2
  • 8
  • 32