Spring mvc + hibernate 的框架中,在非Controller下使用@Autowired注入失败,空指针异常。

Spring mvc + hibernate 的框架中,在非Controller下使用@Autowired注入失败,空指针异常。
配置文件中已经加入了如下的内容
<context:component-scan base-package="com.cnwaterinfo.csp.*"/>
<!-- 使用annotation 自动注册bean,并保证@Required,@Autowired的属性被注入 -->
<context:component-scan base-package="com.cnwaterinfo.csp.">
<context:exclude-filter type="regex" expression=".*.*Controller$" />
</context:component-scan>
Service类:
@Service("realtimeDataService")
@Transactional
public class RealtimeDataServiceImpl implements RealtimeDataService {

@Autowired
private RealtimeDataDao rdd;

....
何解?

简单来说Spring Framework是一个运行时对象管理容器。只有受它管理的对象,才可以通过@Autowired注解来获取另外一个受它管理的对象。

也就是说你的Dao、Service文件一样需要被Spring扫描到并管理。解决方法是以配置Controller等方式配置Dao和Service。

如:

//扫描Dao和Service实现类包
<context:component-scan base-package="com.cnwaterinfo.csp.service">  
<context:component-scan base-package="com.cnwaterinfo.csp.dao">


根据JPA规范,建议使用@Resource注解来获取对象。

温馨提示:答案为网友推荐,仅供参考

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网