【问题标题】:spring rmi @autowired return nullspring rmi @autowired 返回 null
【发布时间】:2015-11-17 21:37:23
【问题描述】:

我在 RMI 服务中的 @autowired 对象上收到 NULL 指针异常。 我创建了一个简单的(我认为)服务,可以通过 RMI 从客户端调用。代码如下

package com.edvs.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.edvs.dao.HostStatusDao;

@Controller
public class HeartbeatImpl implements Heartbeat {

  private static final long serialVersionUID = 7502560843009449650L;

  @Autowired
  private HostStatusDao hs;

  @Override
  public int update(String hostSequenceNumber) {
    int cnt = hs.update(hostSequenceNumber);
    return cnt;
  }

}//End of file HeartbeatImpl.java.

heartbeat-servlet.xml代码如下:

<bean id="heartbeatBean" class="com.edvs.service.HeartbeatImpl">
  <!-- Nothing here for now. -->
 </bean>

<bean class="org.springframework.remoting.rmi.RmiServiceExporter">
 <!-- does not necessarily have to be the same name as the bean to be exported -->
 <property name="serviceName" value="Heartbeat"/>
 <property name="service" ref="heartbeatBean"/>
 <property name="serviceInterface" value="com.edvs.service.Heartbeat"/>
 <!-- defaults to 1099 -->
 <property name="registryPort" value="1199"/>
</bean>

指定组件扫描的我的 WebConfiguration 文件如下:

@Configuration
@EnableWebMvc
@EnableTransactionManagement
@ComponentScan({ "com.edvs.controller","com.edvs.service" })
public class WebConfiguration extends WebMvcConfigurerAdapter {

我的 HeartbeatImpl.java 位于 com.edvs.service 包中,因此应该对其进行扫描,并且应该实例化 @autowired HostStatusDao,但事实并非如此。属性 hs 为 NULL,会产生 NULL 异常。

我在这个系统中有许多控制器使用完全相同的@Autowired 技术,它们工作正常。对象被实例化。我怀疑此类失败是因为 heartbeat-servlet.xml 文件中的 Bean 定义。我在这里解决问题真的很茫然。我一定错过了一些阻止捕获@Autowired 的扫描仪工作的东西。任何帮助将不胜感激。

【问题讨论】:

    标签: spring servlets rmi autowired


    【解决方案1】:

    如果我浪费了任何人的时间,我很抱歉,但我想我在大云中找到了答案。我像这样添加了ApplicationContextAware接口。

    public class HeartbeatImpl implements Heartbeat, ApplicationContextAware {
    

    这需要方法 setApplicationContext。在该方法中,我实例化了我的属性 hs。

        @Override
    public void setApplicationContext(ApplicationContext ctx)
      throws BeansException {
      hs = (HostStatusDao) ctx.getBean("HostStatusDao");
    
    }
    

    我希望这对其他人有所帮助,因为我花了一整天的时间才弄清楚这一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-13
      • 2017-04-23
      • 2022-10-13
      • 2016-10-28
      • 1970-01-01
      • 2014-12-15
      • 2015-08-07
      • 2016-09-09
      相关资源
      最近更新 更多