AOP建议不适用于Builder模式

时间:2019-03-07 08:31:13

标签: java aop aspectj builder

使用构建器模式时,我对AOP建议有疑问。 当我不使用Builder时,一切正常。我的方面:

@Aspect
public class LoggingAspect {
private final String POINTCUT = "execution(* com.project.my.spring.Triangle.*(..))";

@Around(POINTCUT)
public Object aroundMethodAdvice(ProceedingJoinPoint joinPoint) {
    System.out.println("Executing method: " + joinPoint.toString());

    Instant startTime = Instant.now();
    Object value = joinPoint;
    try {
        value = joinPoint.proceed();
    } catch (Throwable e) {
        e.printStackTrace();
    }
    Instant endTime = Instant.now();

    System.out.println("Ending method advice. Execution time of " + joinPoint.toString() + " method is "
            + Duration.between(startTime, endTime).getNano() + " nanoseconds.");

    return value;

    }
}

三角形类:

package com.project.my.spring;

public class Triangle {

    private String message;

    public void someTriangleMethod(){
    System.out.println("Inside com.project.my.spring.Triangle class. Have fun!");
    }

    public static class Builder {
        private final String message;

        public Builder (String message){
            this.message = message;
        }

        public Triangle build() {
            return new Triangle(this);
        }
    }
    private Triangle(Builder builder) {
        message = builder.message;
    }
}

所有输出为:在com.project.my.spring.Triangle类中。玩得开心!

我需要具备: 执行方法... 内... 结束方法...

我在配置类中为Triangle添加了一个bean,它现在可以工作,但是为什么呢?

@Configuration
@EnableAspectJAutoProxy
public class ShapeConfig {

    @Bean
    public LoggingAspect loggingAspect() { return new LoggingAspect();}

    @Bean
    public Triangle.Builder buildTriangle(){
        return new Triangle.Builder("Builder message.");
    }

    @Bean
    public Triangle triangle() {
        return buildTriangle().build();
    }/**/
}

我之前尝试过:

Triangle triangle = builder.build();
triangle.someTriangleMethod();

为什么不起作用?

0 个答案:

没有答案