在我们使用Java开发中,有很多项目中,需要在bean初始化之前,预先处理一些东西(例子:socket的使用)。我们可以考虑使用Spring的ApplicationListener类, 如从配置服务器上获取服务启动配置参数,这个类可以使用org.springframework.context.event包下面的所有事件,我们可以使用ContextRefreshedEvent来保证绝对的第一个执行。
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
@Component
public class ApplicationListenerImp implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent arg0) {
System.out.println("aaa");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("bbb");
}
}