Java监听器中获取service实例

qingwuyun-banner.jpeg

JAVA.jpg

public class WebContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContextEvent.getServletContext());
        ISrInforService srInforService = applicationContext.getBean(ISrInforService.class);
//        ISrInforService srInforService = (ISrInforService) applicationContext.getBean("srInforService");
        srInforService.countAllSrInforsScore();
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}
ISrInforService srInforService = applicationContext.getBean(ISrInforService.class);

ISrInforService srInforService = (ISrInforService) applicationContext.getBean("srInforService");

都可以。

然后配置web.xml

<!-- Spring监听配置,Web容器启动自动装配ApplicationContext的配置信息-->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

参考:

  1. 在监听器中注入spring bean
  2. Java 的监听器中使用 Spring 框架中的某些 service
赞(0)
未经允许禁止转载:优米格 » Java监听器中获取service实例

评论 抢沙发

合作&反馈&投稿

商务合作、问题反馈、投稿,欢迎联系

广告合作侵权联系