I have a module with name "CacheService" which do some cache works, it has a method named "preheatCache" which build cache content when started. The "CacheService" referenced by both web application server and task application server. The web server and task serve started independently, when the task server started, I don't want "preheatCache" executed. How could I implement this?
the code in CacheService that call preheatCache automatically when start server:
@EventListener(ContextRefreshedEvent.class)
public void afterStartup() {
preheatCache();
}
private preheatCache(){
// build cache content
}
the event triggered both in web server and task server.
I trid @ConditionalOnWebApplication
like this
@ConditionalOnWebApplication
private preheatCache(){
// build cache content
}
but it seems not work
Is there some annotation or Spring's mechanism which act on a method, make this method only called in web server?
It must be a public method to allow AOP to kick in
@ConditionalOnWebApplication
public void preheatCache(){
// build cache content
}
and must NOT be invoked from bean itself - so you must self inject that bean and use injection for invocation
@Autowired
private BeanContainingThatMethod self;
@EventListener(ContextRefreshedEvent.class)
public void afterStartup() {
self.preheatCache();
}
If I were you I would create dedicated bean for that (unless this is the one) and annotate whole bean. This way whole bean will be created and managed only if web context is present and will be skipped from creation otherwise.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments