将Service bean自动装配到Spring中的XML定义bean中

时间:2013-01-18 17:05:06

标签: java spring spring-mvc

在我的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;

始终为空。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

将此添加到您的上下文xml文件中:

<context:component-scan base-package="com.myproject.core.security" />

指定后,您的注释将被处理,您的组件将由Spring识别。

如果您还没有,则还需要在应用程序XML中包含类路径和上下文命名空间的spring-context依赖项。

阅读本文:http://www.mkyong.com/spring/spring-auto-scanning-components/可能会有所帮助

答案 1 :(得分:0)

你没有提供足够的信息。哪个春季版?哪个应用服务器?

一般来说,你应该

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

在你的spring xml conf文件中使用带注释的bean。

然而,它并不总是有效。

我遇到了弹簧2.5.6 + Jboss AS7的问题。 Jboss继续报告未定义的注释bean。 (NoSuchBeanDefinition或类似的东西)。我切换到spring 3.0.0.Relase来解决它。

相关问题