如何在“Spring”数据存储库方法“之前”打印一些日志,而不使用自定义存储库

时间:2017-10-29 05:54:56

标签: spring-data spring-aop spring-aspects

我有一个Spring数据存储库。 调用http://localhost:8080/persons webservice时,我想记录一些内容。我不想制作MyCustomRepository<>。更清洁的选择?

回购课程:

#container {height: 100%;}

示例日志:

@RepositoryRestResource(collectionResourceRel = "persons", path = "persons")
public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {

    List<Person> findByLastName(@Param("name") String name);

1 个答案:

答案 0 :(得分:1)

您可以创建一个方面来拦截对PersonRepository的呼叫。从那里,您可以访问OAuth2访问令牌和安全上下文来检索主体。这是一个例子,

@Component
@Aspect
@Log
public class SecurityAspect {

    @Autowired
    private OAuth2ClientContext oauth2ClientContext;

    @Pointcut("execution(public * my.example.repository.PersonRepository.*(..))")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object advice(ProceedingJoinPoint pjp) throws Throwable {
        log.info(
                "Entering SecurityAspect.advice() in class "
                        + pjp.getSignature().getDeclaringTypeName()
                        + " - method: " + pjp.getSignature().getName());

        OAuth2AccessToken accessToken = oauth2ClientContext.getAccessToken();
        log.info("AccessToken: " + accessToken);

        if (SecurityContextHolder.getContext().getAuthentication()
                instanceof OAuth2Authentication) {
            OAuth2Authentication authentication =
                    (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
            if (authentication.getUserAuthentication() instanceof UsernamePasswordAuthenticationToken) {
                UsernamePasswordAuthenticationToken userToken =
                        (UsernamePasswordAuthenticationToken) authentication.getUserAuthentication();
                log.info("Principal id: " + userToken.getPrincipal());
                if (userToken.getDetails() instanceof Map) {
                    Map details = (Map) userToken.getDetails();
                    log.info("Principal Name: " + details.get("name"));
                }
            }
        }

        return pjp.proceed();
    }
}