要在 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