webservice服务中spring注解无法注入资源
在一个项目中需要提供webservice服务,又要在服务中调用Service层的业务逻辑,于是在webservice中用注解注入资源,结果调用webservice一直报空指针,Debug程序时发现要用到的Bean没有成功注入,然后发现注解似乎没起作用
文章目录
applicationContext.xml:
我的配置文件已经开启扫描了
<context:component-scan base-package="com.wcz" />
context:annotation-config:注解扫描是针对已经在Spring容器里注册过的Bean
context:component-scan:不仅具备context:annotation-config的所有功能,还可以在指定扫描的package以及下面的子包
Service类:
webservice类中注解无效:
注解不起作用,只好用代码初始化资源,从类路径ClassPath中寻找指定的XML配置文件,找到并装载完成ApplicationContext的实例化工作
解决方案:
@WebService
public class User {
private static DataServicesImpl dataServices;
static {
//装载单个配置文件实例化ApplicationContext容器
ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
dataServices = (DataServicesImpl) ctx.getBean("DataServicesImpl");
}
@WebMethod
public String getModifyUserToken(){
//业务逻辑
}
}
这里附上ApplicationContext接口的常用实现类介绍
上面使用的ClassPathXmlApplicationContext加载多个配置文件
//装载多个配置文件实例化ApplicationContext容器
String[] configs = {"bean1.xml","bean2.xml","bean3.xml"};
ApplicationContext cxt = new ClassPathXmlApplicationContext(configs);
FileSystemXmlApplicationContext
从指定的文件系统路径中寻找指定的XML配置文件,找到并装载完成ApplicationContext的实例化工作。
//装载单个配置文件实例化ApplicationContext容器
ApplicationContext cxt = new FileSystemXMLApplicationContext("beans.xml");
//装载多个配置文件实例化ApplicationContext容器
String[] configs = {"c:/beans1.xml","c:/beans2.xml"};
ApplicationContext cxt = new FileSystemXmlApplicationContext(configs);
XmlWebApplicationContext
从Web应用中寻找指定的XML配置文件,找到并装载完成ApplicationContext的实例化工作。这是为Web工程量身定制的,使用WebApplicationContextUtils类的getRequiredWebApplicationContext方法可在JSP与Servlet中取得IoC容器的引用
ServletContext servletContext = request.getSession().getServletContext();
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);