本文介紹了Spring AOP–通過反射訪問存儲(chǔ)庫自動(dòng)生成的字段的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
這是第一次在AspectJ中,我可能需要訪問存儲(chǔ)庫的本地私有自動(dòng)連接字段,以便準(zhǔn)確地在該實(shí)例上執(zhí)行某些操作。
我創(chuàng)建了一個(gè)切入點(diǎn),重點(diǎn)放在每個(gè)@Repository
注釋類的每個(gè)方法上。當(dāng)切入點(diǎn)觸發(fā)時(shí),我獲取要從中獲取bean
字段的當(dāng)前類實(shí)例。
這是辦法:
@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
,即使我改為創(chuàng)建類似private | public | package String something = "blablabla";
的內(nèi)容。
我已確保在應(yīng)用程序啟動(dòng)時(shí)實(shí)際實(shí)例化了”Bean”(使用調(diào)試器進(jìn)行了驗(yàn)證)。
我關(guān)注了How to read the value of a private field from a different class in Java?
我錯(cuò)過了什么?|有可能嗎?|有沒有其他方法?
推薦答案
@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();
}
}
}
}
這篇關(guān)于Spring AOP–通過反射訪問存儲(chǔ)庫自動(dòng)生成的字段的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,