logger aop-intercept对公共方法的所有调用

mspsb9vt  于 2021-07-22  发布在  Java
关注(0)|答案(1)|浏览(333)

我需要解决这个问题:
在loggeraop类中,使用spring aop,截获对使用logexecution注解注解的公共方法的所有调用,并在logger字段上调用log方法,截获的方法的名称作为数据参数。

import org.aspectj.lang.*;
    import org.aspectj.lang.annotation.*;
    import org.springframework.context.annotation.*;
    import org.springframework.stereotype.Component;
    import org.springframework.beans.factory.annotation.*;
    import java.lang.annotation.*;
    import java.util.*;

    @Aspect
    @Component
    public class LoggerAOP {
        @Autowired private Logger logger;

        public void loggingAdvice(JoinPoint jp) {

        }

        public static void main(String[] args) {
            AnnotationConfigApplicationContext config = new AnnotationConfigApplicationContext();
            config.register(Config.class);
            config.refresh();

            NameRepository repository = config.getBean(NameRepository.class);
            System.out.println(repository.getNames());
        }
    }
@Component
class NameRepository {
    @LogExecution
    public List<String> getNames() {
        List<String> names = new ArrayList<>();
        names.add("John");
        names.add("Mary");
        return names;
    }
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface LogExecution {}

interface Logger {
    public void log(String data);
}

@Configuration
@EnableAspectJAutoProxy
@Import({LoggerAOP.class, NameRepository.class})
class Config {
    @Bean
    public Logger logger() {
        return (message) -> System.out.println(message);
    }
}

我刚到Spring,所以我还得学点东西。

relj7zay

relj7zay1#

与问题共享的代码作为spring应用程序工作,没有任何问题。基于共享的代码,以下方面将建议使用 @LogExecution Package 内 rg.so 以及它的子 Package 。代码使用 @Around 建议。

@Around("@annotation(logExecution) && within(rg.so..*)")
public Object loggingAdvice(ProceedingJoinPoint pjp, LogExecution logExecution) {
    logger.log("Before method call :"+pjp.getSignature());
    Object obj = null;
    try {
        obj = pjp.proceed();
    } catch (Throwable e) {
        e.printStackTrace();
        logger.log("On error during method call :"+ pjp.getSignature());
    }
    logger.log("After method call :"+pjp.getSignature());
    return obj;
}

参考官方文件
Springaop:https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#aop
关于建议:https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#aop-ataspectj建议
写好切入点:https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#writing-很好的切入点

相关问题