我对Spring的建议一无所知。可以使用两种方式创建具有两个建议的方面:
@Component
@Aspect
public class TestAppli{
private static final Logger LOGGER = LoggerFactory.getLogger(TestAppli.class);
@Pointcut("@annotation(Loggable)")
public void executeLogging(){
}
@Before("executeLogging()")
public void method1(JoinPoint joinPoint){
LOGGER.info("method 1 is called");
}
@Before("executeLogging()")
public void method2(JoinPoint joinPoint){
LOGGER.info("method 2 is called");
}
}
@Component
@Aspect
public class TestAppli {
private static final Logger LOGGER = LoggerFactory.getLogger(TestAppli.class);
@Before("@annotation(Loggable)")
public void method1(JoinPoint joinPoint){
LOGGER.info("method 1 iscalled");
}
@Before("@annotation(Loggable)")
public void method2(JoinPoint joinPoint){
LOGGER.info("method 2 is called");
}
}
[请您解释一下何时必须使用第二项操作?人们说它允许某些东西,但我不知道这是什么。
首先,您需要了解切入点和建议的基础。
第二,这些基于注释的配置只是配置方面的一种方式。因此,不要将其视为“带有切入点注释的空方法”,而是将其视为使用注释定义切入点的语法。
回到您的问题。
他们两个都只是在定义一些事前建议。第二种方法是将切入点定义直接放入建议定义中,而第一种方法是为切入点命名,并在建议中引用它。
只要知道自己在做什么,就没有对与错。例如,对于仅用于一个或两个建议的非常简单直接的切入点,您可以像第二种方式一样直接将其放入建议中。
但是,通常有意义的是给切入点起一个有意义的名字,并通过参考您的建议来使用它。它为切入点赋予了具体的含义,并使其将来更易于修改。