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?