SSM项目中,普通类中调用Service

来源:互联网 发布:羽毛球鞋 推荐 知乎 编辑:程序博客网 时间:2024/06/05 22:45

一开始在普通类中调用Service,报的空指针异常.

找的的解决方法如下:

1.写一个SpringInit辅助类,代码如下:

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;


import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;


public class SpingInit implements ServletContextListener{

private static WebApplicationContext springContext;

public SpingInit(){
super();
}

@Override
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
}


@Override
public void contextInitialized(ServletContextEvent event) {
springContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext()); 
}
public static ApplicationContext getApplicationContext() {     
        return springContext;    


}


}

2.把该类所在的包要被spring扫描

<context:component-scan base-package="com.test.utils" />

3.在web.xml中加入该类的监听事件

<listener>
    <listener-class>com.test.utils.SpingInit</listener-class>
  </listener>

4.在普通类中调用:

NotifyManagementInfoService notifyManagementInfoService = 
(NotifyManagementInfoService) SpingInit.getApplicationContext().getBean("notifyManagementInfoServiceImpl");


若不知道bean的被命名成什么,可在xml中加入

<bean id=" testService" class="com.yzx.crbt.service.impl.CustomerServiceImpl" />

会报expected single matching bean but found 2: testService,customerServiceImpl异常,可查看bean被命名成什么....

我小白一个,在这里的时候还吃亏了...


好了,终于可以在普通类中进行操作了

notifyManagementInfoService.add(notifyManagementInfo);

参考博客:http://www.cnblogs.com/chongerlishan/p/5942033.html

原创粉丝点击