欢迎光临
感受代码之美

Java监听器中获取service实例

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
转载请注明来源:四个空格 » Java监听器中获取service实例

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址