[英]Spring AOP advice with method rather than @annotation : Why?
我不明白 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");
}
}
拜托,你能解釋一下什么時候必須使用第二個操作嗎? 人們說它允許某些東西,但我不明白這是什么東西。
首先,您需要了解什么是切入點和建議的基礎知識。
其次,這些基於注解的配置只是配置Aspects的一種方式。 因此,不要將其視為“帶有切入點注釋的空方法”,而是將其視為使用注釋定義切入點的語法。
回到你的問題。
他們都只是簡單地定義了一些事前建議。 在第二種方式中,您將切入點定義直接放入建議定義中,而在第一種方式中,您為切入點命名,並在您的建議中引用它。
只要您知道自己在做什么,就沒有對錯之分。 例如,對於非常簡單直接的切入點,僅在一兩個通知中使用,您可以像第二種方式一樣將其直接放在通知中。
但是,通常為切入點指定一個有意義的名稱並通過在您的建議中引用來使用它是有意義的。 它為您的切入點賦予語義意義,並使其在將來更容易修改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.