Custom annotation issue?

34 Views Asked by At

Annotation

@Target(ElementType.METHOD) // Annotation can be applied to methods
@Retention(RetentionPolicy.RUNTIME) // Annotation will be retained at runtime
public @interface MethodExecutionTime {
} 

Aspect class

@Aspect
@Component
public class MethodExecutionTimeAspect {
    private static final Logger logger = LoggerFactory.getLogger(MethodExecutionTimeAspect.class);
    @Around("@annotation(com.teamsapi.custom_annotation.annotation.MethodExecutionTime)")
    public Object measureExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long endTime = System.currentTimeMillis();
        long executionTime = endTime - startTime;
        logger.warn("Method '{}' took {} milliseconds to execute.", joinPoint.getSignature().toShortString(), executionTime);
        return result;
    }
}

config

dependencies {
    implementation 'org.jsoup:jsoup:1.15.3'
    implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    implementation 'org.springframework:spring-aop:5.3.9'
    implementation 'org.aspectj:aspectjweaver:1.9.7'
}


plugins {
    id 'java'
    id 'org.springframework.boot' version '3.1.0'
    id 'io.spring.dependency-management' version '1.1.0'
}

this is a method in service class, not working for it

@MethodExecutionTime
    private String responseDataReceived(String url) {
       return "code";
    }

how to execute this code properly tell me any way to implement it properly working fine for some method while not for some method, why it is not working tell me the way to resolve it

1

There are 1 best solutions below

0
kriegaex On

Inspecting your code, ...

@MethodExecutionTime
private String responseDataReceived(String url) {
  return "code";
}

... I see that the annotated method is private. Spring AOP is proxy-based, and dynamic proxies technically are subclasses. A subclass in Java cannot see or call its parent's private methods, hence the term "private". I.e., you can only intercept public methods (both JDK interface proxies and CGLIB proxies) and protected or class-scopend methods (CGLIB only) using Spring AOP. You would need native AspectJ to intercept private ones, too. But actually, if the method is worth being intercepted, why would it be private, i.e. an implementation detail hidden from the outside world?

P.S.: What is "sustome" supposed to mean?