2011-04-28 52 views
0

我正在研究JAX-WS项目,现在我想为我的一个实用程序添加依赖项注入。在JAX-WS项目中使用DI与Spring一起使用时的NPE

该实用程序有一个接口; 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 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配置实际上是正确的。

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

任何帮助是极大的赞赏。

回答

2

虽然从你的帖子不清楚,我怀疑你不从应用程序上下文中检索实例。如果你不使用任何注释,然后调用代码为MyService的对象需要做这样的事情来从应用程序上下文中的bean:

ServletContext servletContext =this.getServletContext(); 

WebApplicationContext wac = WebApplicationContextUtils. 
getRequiredWebApplicationContext(servletContext); 

MyService user = (MyService)wac.getBean("myService"); 

您提供Spring的配置是正确的。您只需确保应用程序上下文已创建,并且您正在从应用程序上下文中取回对象。在这里看到更多的信息:

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

+0

谢谢您提供丰富的答案。从我的答案中可以得知,我可以避免必须通过带注释的AppContext获取bean?我之前只使用过Wicket项目的Spring,并且在这些项目中我可以使用名为“@SpringBean”的注释。对于普通的Spring有没有这种注释的等价物? – John 2011-04-28 20:35:58

+1

您可以使用@Autowired连接服务或@Resource。这两个注释都有优缺点。看看春天的文档。但是,您必须将web配置为注入依赖关系,这意味着您必须添加如下所示: 添加到您的应用程序上下文中(请参阅:http://static.springsource.org/spring/ docs/3.0.x/spring-framework-reference/html/beans.html#beans-annotation-config)可能会有一些其他的配置,你必须做,因为你没有使用spring-mvc。 – 2011-04-28 20:41:33

2

你应该从Spring上下文的服务实例。

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

相关问题