2017-08-01 62 views
0

我已經使用本教程Accessing JPA Data with REST來創建一個簡單的RESTful Web服務,它可以訪問數據庫中的某些數據。它效果很好。我喜歡它的簡單程度,我也多少了解它是如何工作的。具有REST日誌的Spring JPA數據

但是,有人問我要添加一些自定義日誌記錄。每當Web服務被調用日誌時,都會生成「開始 - 時間」,並在服務返回之前生成另一個日誌「結束 - 時間」。有沒有辦法做到這一點,而不破壞我的包含@Query anotation

public interface PersonRepository extends PagingAndSortingRepository<Person, Long> 

方法我是那種跳躍會有某種註解,但我似乎無法找到任何東西。

有什麼建議嗎?

回答

2

聽起來就像是Spring-AOP的情況!

very helpful tutorial(也是一個useful SO answer),我颳起了東西,之前在我TokenRepository執行任何方法後

@Repository 
public interface TokenRepository extends CrudRepository<Token, String> { 
} 

和有趣的一點是

import org.aspectj.lang.JoinPoint; 
import org.aspectj.lang.annotation.AfterReturning; 
import org.aspectj.lang.annotation.Aspect; 
import org.aspectj.lang.annotation.Before; 
import org.aspectj.lang.annotation.Pointcut; 
import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import org.springframework.stereotype.Component; 

@Aspect 
@Component 
public class LoggingHandler { 

    Logger log = LoggerFactory.getLogger(this.getClass()); 

    @Pointcut("this(org.springframework.data.repository.Repository)") 
    public void repository() { } 

    @Pointcut("execution(* *.*(..))") 
    protected void allMethod() { } 

    //before -> Any resource annotated with @Repository annotation 
    //and all method and function 
    @Before("repository() && allMethod()") 
    public void logBefore(JoinPoint joinPoint) { 
     log.info("Entering in Method : " + 
joinPoint.getSignature().getName() + " at " + System.currentTimeMillis()); 
    } 

    //After -> All method within resource annotated with @Repository annotation 
    @AfterReturning(pointcut = "repository() && allMethod()") 
    public void logAfter(JoinPoint joinPoint) { 
     log.info("Method Returned at : " + System.currentTimeMillis()); 
    } 
} 
+0

謝謝您登錄工作順便說一句 – Francisco

+0

這工作就像一個魅力。我只需要熟悉AOP – Francisco

+0

如果我想在logBefore()和logAfter()方法之間傳遞變量,該怎麼辦?例如,一個標識符使得前面的日誌會顯示爲「98f473ea-f333-4278-adf1-b70eba4c9338 - START - 2017-008-08 10:10:00」,後面的日誌會顯示爲「98f473ea-f333-4278-adf1- b70eba4c9338 - END - 2017-008-08 10:10:10「。基本上某種標識符將標識對該方法的調用的開始和結束 – Francisco