[英]How do i get the call stack/caller of the method defined as pointcut when the advice is applied in Spring AOP?
[英]Spring: How do I call a method only when in web application?
我有一個名為“CacheService”的模塊,它做一些緩存工作,它有一個名為“preheatCache”的方法,它在啟動時構建緩存內容。 Web 應用程序服務器和任務應用程序服務器都引用的“CacheService”。 web服務器和任務服務獨立啟動,當任務服務器啟動時,我不想執行“preheatCache”。 我怎么能實現這個?
CacheService 中啟動服務器時自動調用 preheatCache 的代碼:
@EventListener(ContextRefreshedEvent.class)
public void afterStartup() {
preheatCache();
}
private preheatCache(){
// build cache content
}
該事件同時在 Web 服務器和任務服務器中觸發。
我像這樣試過@ConditionalOnWebApplication
@ConditionalOnWebApplication
private preheatCache(){
// build cache content
}
但它似乎不起作用
是否有一些注釋或 Spring 的機制作用於一個方法,使這個方法只能在 Web 服務器中調用?
它必須是允許 AOP 啟動的公共方法
@ConditionalOnWebApplication
public void preheatCache(){
// build cache content
}
並且不能從 bean 本身調用 - 因此您必須自注入該 bean 並使用注入進行調用
@Autowired
private BeanContainingThatMethod self;
@EventListener(ContextRefreshedEvent.class)
public void afterStartup() {
self.preheatCache();
}
如果我是你,我會為此創建專用的 bean(除非這是一個)並注釋整個 bean。 這樣,只有在存在 Web 上下文時才會創建和管理整個 bean,否則將從創建過程中跳過。
您可以使用@ConditionalOnWebApplication
注冊一個單獨的 bean,以便它僅在 web 應用程序運行時注冊。 然后這個 bean 可以注入您的CacheService
並調用您的 preheatCache 方法。 這個額外的 bean 可能如下所示:
@Component
@ConditionalOnWebApplication
public class CachePreheater
{
private CacheService cacheService;
public CachePreheater(CacheService cacheService) {
this.cacheService = cacheService;
}
@EventListener(ContextRefreshedEvent.class)
public void afterStartup() {
this.cacheService.preheatCache();
}
}
要使此代碼起作用,您必須調整 preheatCache 方法的可見性。
一種不同的方法,您可以為 web、task-server 維護兩個配置文件。
您可以像下面那樣手動初始化它。
@Service
public class CacheService {
@Profile("web")
@PostConstruct
public void pstConstruct(){
this.preheatCache()
}
private preheatCache(){
// build cache content
}
}
在 Profile 注釋中,您可以使用任何布爾屬性值,例如 ${property.value} 並將其用於不同的用例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.