@Autowired注入为null,空指针异常。

Spring mvc + hibernate 的框架中,在非Controller下使用@Autowired注入失败,空指针异常。
配置文件中已经加入了如下的内容

<!-- 使用annotation 自动注册bean,并保证@Required,@Autowired的属性被注入 -->




/context:component-scan
Service类:
@Service("realtimeDataService")
@Transactional
public class RealtimeDataServiceImpl implements RealtimeDataService {

@Autowired
private RealtimeDataDao rdd;

....
在非Controller下
public class NetWorkPascalRealtimeDataHandler {

private final static Logger log = Logger
        .getLogger(NetWorkPascalRealtimeDataHandler.class);

@Autowired
private RealtimeDataService realtimeDataService; 
.....



此时realtimeDataService为NULL,调用任何方法都会空指针异常

何解?

RealtimeDataDao 这个类你写注解了么?还有用XML配置了么?名称对么

@Controller
public class NullDebugController {
@GetMapping("/null")
public String handle(@Autowired Report testReport,@RequestParam String time,Model model) {
System.out.println("soso: "+ testReport);//object
System.out.println(testReport.base);//这个为啥是null 呢
return "view";
}
}

@Service("testReport")
class Report {
String demo = "report";
@Autowired
public Base base;

}

@Service
class Base {
String demo = "demo";
}

XML文件配置的问题,你没有扫描"在非Controller下.."这个类所在的文件,Spring不知道你这个东西在哪