本文介紹了用于數(shù)據(jù)庫(kù)操作的Spring AOP的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我在一個(gè)Spring中工作,Hibernate項(xiàng)目和數(shù)據(jù)庫(kù)是Oracle。我有用于持久化相關(guān)操作的DAO層。
在我的所有表中,我有create_date
和update_date
列分別表示在表中插入和更新行時(shí)的時(shí)間戳。
有一個(gè)要求,每當(dāng)發(fā)生任何插入/更新操作時(shí),我都必須更新該特定表的上述兩個(gè)時(shí)間戳列。例如,如果我的DAO層有兩個(gè)方法,假設(shè)m1和m2分別負(fù)責(zé)影響T1和T2表?,F(xiàn)在,如果調(diào)用M1方法,則T1表的時(shí)間戳列將被更新。對(duì)于插入,create_date
列將被更新,而對(duì)于任何更新,update_date
列將被更新。
我對(duì)Spring AOP有想法,所以我想用AOP來實(shí)現(xiàn)上面的需求,但我不太確定是否可以用AOP來實(shí)現(xiàn)。
如果我可以使用AOP來滿足這個(gè)要求,請(qǐng)告訴我。如果可能,請(qǐng)向我提供如何實(shí)施它的輸入。
推薦答案
我已經(jīng)使用Spring AOP為我的應(yīng)用程序中的一個(gè)模塊實(shí)現(xiàn)了更新日期功能。
供您參考的PFB代碼
希望這將有所幫助。
我想知道是否可以對(duì)變量也有切入點(diǎn)。我知道這在Spring的方面j實(shí)現(xiàn)中可能是不可能的。但是任何解決辦法:p
**
* @author Vikas.Chowdhury
* @version $Revision$ Last changed by $Author$ on $Date$ as $Revision$
*/
@Aspect
@Component
public class UpdateDateAspect
{
@Autowired
private ISurveyService surveyService;
Integer surveyId = null;
Logger gtLogger = Logger.getLogger(this.getClass().getName());
@Pointcut("execution(* com.xyz.service.impl.*.saveSurvey*(..)))")
public void updateDate()
{
}
@Around("updateDate()")
public Object myAspect(final ProceedingJoinPoint pjp)
{
// retrieve the runtime method arguments (dynamic)
Object returnVal = null;
for (final Object argument : pjp.getArgs())
{
if (argument instanceof SurveyHelper)
{
SurveyHelper surveyHelper = (SurveyHelper) argument;
surveyId = surveyHelper.getSurveyId();
}
}
try
{
returnVal = pjp.proceed();
}
catch (Throwable e)
{
gtLogger.debug("Unable to use JointPoint :(");
}
return returnVal;
}
@After("updateDate()")
public void updateSurveyDateBySurveyId() throws Exception
{
if (surveyId != null)
{
surveyService.updateSurveyDateBySurveyId(surveyId);
}
}
}
這篇關(guān)于用于數(shù)據(jù)庫(kù)操作的Spring AOP的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,