• spring 初始化时注入bean实现listener的方法


    两种方法:

    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
    }
    }
    }

  • 相关阅读:
    Android ViewPager使用详解
    Android开发 侧边滑动菜单栏SlidingMenu结合Fragment
    ArrayList
    Gstreamer中加入�x265编解码器
    python fabric实现远程操作和部署
    java.text.NumberFormat使用方法
    Delphi 2007体验!
    Codeforces 360C Levko and Strings dp
    FindWindow使用方法
    C++ Primer 学习笔记_87_用于大型程序的工具 --异常处理
  • 原文地址:https://www.cnblogs.com/anruy/p/5749476.html
Copyright © 2020-2023  润新知