这是我第一次需要在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?
我缺少什么? |可能吗? |有什么不同的方法吗?
答案 0 :(得分:0)
@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();
}
}
}
}