所以我有一个 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类检测为组件......