是否有Spring AOP批注,仅当该批注返回true时,才允许我们进入方法内部?

时间:2018-12-15 10:18:25

标签: java spring annotations spring-aop spring-annotations

是否存在Spring AOP批注,仅当该批注返回true时,该批注才允许我们进入方法内部?

我想要这样的东西:

@CustomAnnotation
public String foo(){
System.out.println("Hello World");
return "foo";
}

所以现在只有当@CustomAnnotation返回true时,我们才进入foo()方法并打印Hello World并返回字符串“ foo”,但是@CustomAnnotation返回false时-我们将不进入foo ()方法。

1 个答案:

答案 0 :(得分:0)

要在Spring中使用AOP,应将其添加到pom.xml

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-aop</artifactId>
  <version>5.0.1.RELEASE</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjweaver</artifactId>
  <version>1.8.12</version>
  <scope>compile</scope>
</dependency>

或者只有一个依赖于Spring Boot项目

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

要创建自定义注释,我们需要SkipOnCondition.java

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

我们需要配置方面EchoAspect.java。为了能够跳过方法,我们选择了Around截取点。拦截的触发器将指定注解。 ProceedingJoinPoint可以提供有关所拦截方法的所有详细信息。例如:参数,签名,...

@Aspect
@Configuration
public class EchoAspect {
    private Logger logger = LoggerFactory.getLogger(EchoAspect.class);

    @Around("@annotation(com.example.demo.aop.SkipOnCondition)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        if ("skip".equals((String) joinPoint.getArgs()[0])){
            logger.info("Condition is true the method will be skipped.");
            return null;
        }
        return joinPoint.proceed();
    }
}

被测对象Echo.java具有void和具有返回类型的方法。

@Component
public class Echo {

    private Logger logger = LoggerFactory.getLogger(Echo.class);

    @SkipOnCondition
    public String echo (String s) {
        return s;
    }

    @SkipOnCondition
    public void blindEcho (String s) {
        logger.info(s);
    }
}

和概念证明EchoTest.java

@RunWith(SpringRunner.class)
@SpringBootTest
public class EchoTest {
    private Logger logger = LoggerFactory.getLogger(EchoTest.class);

    @Autowired
    private Echo echo;

    @Test
    public void testEcho() {
        echo.blindEcho("boom");
        echo.blindEcho("skip");
        logger.info(echo.echo("boom"));
        logger.info(echo.echo("skip"));
    }
}

输出将向我们展示其工作方式。 echo.blindEcho("boom");不满足条件,将按预期执行。 echo.blindEcho("skip");将被截取,因为结果只会显示特殊的日志记录消息。 logger.info(echo.echo("boom"));```` doesn't satisfy the condition and will be executed as expected. logger.info(echo.echo(“ skip”)));`''将被截取,因为结果将显示特殊的日志消息,并且由于该方法具有返回类型,因此该日志记录器将输出null。

com.example.demo.aop.Echo                : boom
com.example.demo.aop.EchoAspect          : Condition is true the method will be skipped.
com.example.demo.aop.EchoTest            : boom
com.example.demo.aop.EchoAspect          : Condition is true the method will be skipped.
com.example.demo.aop.EchoTest            : null

具有更多详细信息的好例子,link