使用spring 监听器

使用了springmvc,如果要使用监听器,如果使用传统的web监听器(ServletContextListener),那么启动时,加载顺序就要特别注意,否则在监听器中是得不到spring管理的bean的,所以既然使用了spring,还是尽量使用spring提供的东西,监听器也是如此,使用spring提供的ApplicationListener

创建如下的类即可在启动服务时调用(都无需配置web.xml)


import javax.annotation.Resource;

import org.springframework.context.ApplicationListener;

import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@Component
public class ScheduleListener implements ApplicationListener<ContextRefreshedEvent> {

    @Resource
    private TestService testService;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        // TODO Auto-generated method stub
        // 防止重复执行
        if (event.getApplicationContext().getParent() != null) {
            System.out.println("已经执行过了");
            return;
        }
        System.out.println(testService.getClass());
        List<String> secondSwitchList = testService.getCdnpointList("statis_second");
        System.out.println(secondSwitchList);
    }

}

 

posted on 2017-07-04 14:25  耐旺旺  阅读(325)  评论(0编辑  收藏  举报

导航