0

所以我有一个 spring 应用程序,我添加了一个使用注解的 loggingHandler 类以及一个 @Loggable 自定义注解。我已经成功记录了在@RestController 类中定义的方法调用,但是,注释为@Component 的类似乎没有被spring 检测到......

以下是部分代码:

package company;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;


@SpringBootApplication
@EnableAspectJAutoProxy(proxyTargetClass=true)
@ComponentScan({"company", "document", "logger", "model.bodyComponents"})
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

然后API

package company;

@RestController
public class Api {

    @PostMapping(value = "/", consumes = MediaType.APPLICATION_XML_VALUE)
    @Loggable
    public ResponseEntity<?> convertXmlToPdf(HttpServletRequest request) {
                // some code
                root.render(outputStream); //it is called correctly
                // some code
    }

然后调用的方法渲染:

package company;

@Component
public class Root {

    @Loggable
    public void render(OutputStream target) throws IOException, ParseException, TypesetElementWidthException, ClassNotFoundException {

     //some code  

    }

}

然后是 LoggingHandler:

@Aspect
@Configuration
public class LoggingHandler {

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

    @Pointcut("@annotation(logger.Loggable)")
    public void pcLoggable(){
    }

    @Before("@annotation(logger.Loggable)")
    public void beforeAnnotLog(JoinPoint joinPoint){

        log.info(joinPoint.getSignature() + "Something will be called called with loggable annot.", joinPoint);
        System.out.println("Test Loggable annotation Before the call");

    }

    @After("@annotation(logger.Loggable)")
    public void annotLog(JoinPoint joinPoint){

        log.info(joinPoint.getSignature() + "Something is called with loggable annot.", joinPoint);
        System.out.println("Test Loggable annotation");

    }

}

最后是 Loggable 注释:

package logger;

import java.lang.annotation.*;

@Target({ElementType.TYPE ,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface Loggable {

}

当调用 convertXmlToPdf 时调用记录器(我发布了一个 XML,一切运行正常)。

该方法调用 Root.render 方法,但没有记录任何内容,尽管 Root 是一个组件并且渲染使用 @Loggable 注释。所以这让我觉得spring没有将Root类检测为组件......

4

1 回答 1

1

Api 如何获取对 Root 类的引用?我猜你正在那里做一个新的 Root() 而不是获取 Spring 托管实例。– M. Deinum 7 月 11 日 10:49

是的,有一个新的 Root(),但我不确定为什么我应该使用 spring 托管实例...... – Cromm Jul 11​​ at 11:04

答案很简单:因为 Spring AOP 只适用于 Spring 组件。它创建动态代理,以便向它们注册方面或顾问,并在调用代理方法时执行它们。通过实例化new Root()你绕过了代理创建,因此你不能期望任何 Spring AOP 方面在那里工作。为了将 AOP 应用于非 Spring 管理的对象,您需要使用完整的 AspectJ。

@M。Deinum,我写这个答案是为了结束这个话题。我知道你本可以自己写的,但在 2+ 周内没有写,所以请原谅我从你那里偷了这个。随意写下你自己的答案,然后我会删除我的,你可以接受你的。

于 2019-07-28T05:17:17.653 回答