两种方法:
1、实现ApplicationListener<ContextRefreshedEvent>的onApplicationEvent(ContextRefreshedEvent event)方法
并在application.xml或者spring-servlet.xml中注入bean,如下所示
<bean class="com.ss.pts.util.ContextParaInitialize"></bean>
2、直接使用@postConstruct注解,只要是spring能扫描到的类即可。
@Component
public class ContextParaInitialize implements ApplicationListener<ContextRefreshedEvent> {
private static Logger log = LoggerFactory.getLogger(ContextParaInitialize.class);
public static List<MachineInfoModel> machineList = null;
@Resource IMachineDao machineDao;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
log.info("----start load machine info");
try {
if(event.getApplicationContext().getParent() == null){
machineList = machineDao.getAllMachineInfo();
}
log.info("machine info : "+machineList.get(0).getIp());
} catch (Exception e) {
e.getStackTrace();
log.error("machine info load error :"+e.getMessage());
// TODO: handle exception
}
}
@PostConstruct
public void test (){
log.info("...............................");
log.info("----start load machine info");
try {
machineList = machineDao.getAllMachineInfo();
log.info("machine info : "+machineList.get(0).getIp());
} catch (Exception e) {
e.getStackTrace();
log.error("machine info load error :"+e.getMessage());
// TODO: handle exception
}
}
}