您的位置:首页 > 其它

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

2017-09-15 13:20 351 查看
一开始在普通类中调用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

4000
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: