【发布时间】:2014-05-08 18:06:35
【问题描述】:
applicationContext.xml 上的 bean defiend 正在使用 ClassPathXmlApllicationContext 和 WebApplicationContext 进行实例化。使用前者时,bean 按预期返回,但使用后者时,WebApplicationContext,我得到一个空值。
仅供参考:没有充分利用 Spring。只是用来定义一个bean并初始化它。它是一个基于 jboss 的 Web 服务应用程序。
我在 web.xml 中定义了 WebApplicationContext 如下
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<display-name>Service</display-name>
<servlet-name>MService</servlet-name>
<servlet-class>
com.xyz.atop.ws.memb.MServiceImpl
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MService</servlet-name>
<url-pattern>/Service</url-pattern>
</servlet-mapping>
</web-app>
applicationContext.xml 中的条目
<beans ...>
<context:annotation-config />
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean id="helper" name="helper" class="com.xyz.svc.wrapper.Helper">
<constructor-arg type="java.lang.String" value="ABC"/>
</bean>
</beans>
在我的代码中使用了 ClassPathApplicationContext(按预期返回一个 bean 实例),如下所示
private static Helper helper;
public MServiceImpl() {
}
static {
ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
helper = (Helper) appContext.getBean("helper");
}
......
......
在使用 WebApplicationContext 时,我尝试了 @Autowired 注解,甚至尝试了 setter 注入。两种方式我都返回一个空值。
我试图初始化的“Helper”类来自一个 jar 文件,该文件又调用 cxf-spring 应用程序。
请查看上述场景并建议在使用 WebApplicationCONtext 时摆脱空指针。
【问题讨论】:
标签: java spring dependency-injection applicationcontext