Execute method on startup in spring
Is there any Spring 3 feature to execute some methods when the application starts for the first time? I know that I can do the trick of setting a method with @Scheduled annotation and it executes just after the startup, but then it will execute periodically.
Thanks.
If by "application startup" you mean "application context startup", then yes, there are many ways to do this, the easiest (for singletons beans, anyway) being to annotate your method with @PostConstruct
. Take a look at the link to see the other options, but in summary they are:
@PostConstruct
afterPropertiesSet()
as defined by the InitializingBean
callback interface Technically, these are hooks into the bean lifecycle, rather than the context lifecycle, but in 99% of cases, the two are equivalent.
If you need to hook specifically into the context startup/shutdown, then you can implement the Lifecycle
interface instead, but that's probably unnecessary.
This is easily done with an ApplicationListener
. I got this to work listening to Spring's ContextRefreshedEvent
:
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
@Component
public class StartupHousekeeper implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(final ContextRefreshedEvent event) {
// do whatever you need here
}
}
Application listeners run synchronously in Spring. If you want to make sure you're code is executed only once, just keep some state in your component.
UPDATE
Starting with Spring 4.2+ you can also use the @EventListener
annotation to observe the ContextRefreshedEvent
(thanks to @bphilipnyc for pointing this out):
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
@Component
public class StartupHousekeeper {
@EventListener(ContextRefreshedEvent.class)
public void contextRefreshedEvent() {
// do whatever you need here
}
}
在Spring 4.2中,你现在可以简单地做到:
@Component
class StartupHousekeeper {
@EventListener(ContextRefreshedEvent.class)
void contextRefreshedEvent() {
//do whatever
}
}
链接地址: http://www.djcxy.com/p/50898.html
上一篇: 将Mockito模拟注入到Spring bean中
下一篇: 在春季启动时执行方法