在Spring中将Service bean自动注入到XML定义的bean中

4
在我的Spring应用中,我在xml文件中定义了如下的bean:
<beans:bean id="tokenStore" class="com.myproject.core.security.RemoteTokenStore" />

我还有一个我创建的类,并使用@Service进行了注释:

com.myproject.core.service.CacheService

在我的RemoteTokenStore.java文件中,如果我尝试这样自动注入CacheService:
@Autowired
private CacheService cacheService;

它始终为null。我该如何修复?


有时候混合使用xml定义的bean和对自动装配的引用是很有用的。有人知道怎么做吗? - borjab
2个回答

3
将此添加到您的上下文XML文件中:
<context:component-scan base-package="com.myproject.core.security" />

一旦指定了这个,您的注释将被处理,并且Spring将识别您的组件。
如果您还没有这样做,您还需要在类路径中包含spring-context依赖项和应用程序XML中的上下文命名空间。
阅读此内容:http://www.mkyong.com/spring/spring-auto-scanning-components/ 可能会有所帮助。

这并不完全正确。<context:annotation-config/>足以启用许多注释(如Autowired),但您需要上述扫描来使Spring搜索未在XML中描述的已注释组件。 - vertti
更新了答案,以免误导 :) - cowls

0

你没有提供足够的信息。Spring 版本是哪个?应用服务器呢?

通常情况下,你应该有以下内容:

<context:component-scan base-package="com.packagebase" /> 

在你的Spring XML配置文件中使用注释标记的bean。

但是,它并不总是有效。

我曾在Spring 2.5.6 + Jboss AS7中遇到过问题。Jboss一直报告找不到已定义的注释标记的bean(没有这样的BeanDefinition或类似的东西)。我切换到Spring 3.0.0.Release来解决这个问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接