使用 Spring AOP 作为库的自定义注释不起作用

问题描述 投票:0回答:2

我正在尝试使用自定义注释和 Spring AOP 创建一个 Spring Boot 库。当我将这个库与新的 Spring Boot 应用程序一起使用时。然后它不起作用。即使我也没有收到任何错误。

图书馆样本 -

自定义注释

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

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

Spring AOP 类

@Aspect
class LoggingAspect {
@Around("@annotation(com.demo.commonlogging.aspect.HttpLogger)")
    public Object inControllers(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        return loggingAdvice(proceedingJoinPoint); // Method for implementation
    }
}

pom.xml

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

使用 mvn clean install 创建库

现在新的库已导入到 springboot 应用程序中。

控制器中使用了新的自定义注释

控制器

@RestController
@RequestMapping(value = "/rest/test")
public class RestApiTestControllers {
    @GetMapping
    @HttpLogger
    public String get(){
        return "Hello !";
    }
}

请帮忙。

spring spring-boot spring-aop spring-annotations
2个回答
0
投票

似乎您缺少

@Component
中的
LoggingAspect
,还可以拨打电话继续
proceedingJoinPoint.proceed();
并返回其值。

所以你的代码应该是这样的:


@Aspect
@Component
class LoggingAspect {
    @Around("@annotation(com.demo.commonlogging.aspect.HttpLogger)")
    public Object inControllers(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("Before call");
        Object returned = proceedingJoinPoint.proceed();
        System.out.println("After call");
        return returned;
    }
}

希望这有帮助!


0
投票

有一件事是添加

@Component
就像 neetesh-bhardwaj 提到的那样,但是要从外部库扫描方面,您必须添加

@Import({LoggingAspect.class})

最好在主课的

@SpringBootApplication
下。

这样做的原因是,当从外部库自动加载时,Aspect 可能会对性能等产生重大影响,这在仅添加外部依赖项时可能会导致意外行为。

© www.soinside.com 2019 - 2024. All rights reserved.