【问题标题】:NPE when using DI with Spring in JAX-WS project在 JAX-WS 项目中将 DI 与 Spring 结合使用时的 NPE
【发布时间】:2011-04-28 19:58:58
【问题描述】:

我正在开发一个 JAX-WS 项目,现在我想为我的一个实用程序添加依赖注入。

该实用程序有一个界面; GeocodeUtil,以及两个实现,GeocodeUtilGoogleImpl 和 GeocodeUtilYahooImpl。现在,在我的服务类中,我有以下内容:

public class MyService {
    private GeocodeUtil geocodeUtil;
    /* getter and setter for geocodeUtil */
}

在我的 applicationContext.xml 中,我有以下内容:

<bean id="geocodeUtil" class="com.company.GeocodeUtilGoogleImpl"/>
<bean id="myService" class="com.company.MyService">
    <property name="geocodeUtil" ref="geocodeUtil" />
</bean>

这是我的 web.xml(仅与 Spring 相关的部分):

<!-- Spring context -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>

<!-- Listeners -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

当我创建 MyService 对象的实例并尝试使用 geocodeUtil 时,我得到一个 NullPointerException 并且在我看来该实现没有被注入。 我认为奇怪的是,一旦我删除 getter/setter,应用程序在启动时崩溃,Spring 抱怨缺少 setter/getter,这让我认为 XML 配置实际上是正确的。

我没有使用任何与 spring 相关的 Java 注释。

非常感谢任何帮助。

【问题讨论】:

    标签: spring dependency-injection jax-ws javabeans


    【解决方案1】:

    虽然您的帖子并不清楚,但我怀疑您没有从应用程序上下文中检索实例。如果您没有使用任何注释,那么调用 MyService 对象的代码需要通过执行以下操作从应用程序上下文中获取 bean:

    ServletContext servletContext =this.getServletContext();
    
     WebApplicationContext wac = WebApplicationContextUtils.
    getRequiredWebApplicationContext(servletContext);
    
     MyService user = (MyService)wac.getBean("myService");
    

    您提供的弹簧配置是正确的。您需要做的就是确保创建了应用程序上下文,并且您正在从应用程序上下文中检索您的对象。请参阅此处了解更多信息:

    http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-client

    【讨论】:

    • 感谢您提供的信息丰富的回答。根据我从您的回答中收集到的信息,我可以避免通过带有注释的 AppContext 获取 bean?我之前只在 Wicket 项目中使用过 Spring,在这些项目中我可以使用名为“@SpringBean”的注释。普通 Spring 是否有与此注释等效的注释?
    • 您可以使用@Autowired 连接服务或@Resource。两种注释都有优点和缺点。看看春季文档。但是,您必须配置 Web 以注入依赖项,这意味着您必须添加类似这样的内容: 到您的应用程序上下文(请参阅:static.springsource.org/spring/docs/3.0.x/…)可能会有一些其他配置必须这样做,因为您没有使用 spring-mvc。
    【解决方案2】:

    您也应该从 Spring 上下文中获取 Service 实例。

    使用 new 运算符创建服务对象不会触发 spring 为该实例注入对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-29
      • 2011-12-16
      • 1970-01-01
      • 1970-01-01
      • 2012-10-20
      • 2014-01-08
      • 1970-01-01
      相关资源
      最近更新 更多