java 在 Spring 中将服务 bean 自动装配为 XML 定义的 bean
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14403934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Autowire Service bean into an XML defined bean in Spring
提问by user1007895
In my Spring Application, I have a bean defined in my xml as such:
在我的 Spring 应用程序中,我在我的 xml 中定义了一个 bean,如下所示:
<beans:bean id="tokenStore" class="com.myproject.core.security.RemoteTokenStore" />
I also have this class I created, and annotated with @Service:
我也有我创建的这个类,并用@Service 注释:
com.myproject.core.service.CacheService
In my RemoteTokenStore.java file, if I try to Autowire CacheService like so:
在我的 RemoteTokenStore.java 文件中,如果我尝试像这样 Autowire CacheService:
@Autowired
private CacheService cacheService;
It is always null. How to I fix this?
它始终为空。我该如何解决这个问题?
采纳答案by cowls
Add this to your context xml file:
将此添加到您的上下文 xml 文件中:
<context:component-scan base-package="com.myproject.core.security" />
Once this has been specified your annotations will be processed and your components will be identified by Spring.
一旦指定了这一点,您的注释将被处理并且您的组件将被 Spring 识别。
If you haven't already you will also need to include the spring-context
dependency on your classpath and the context namespace in your application XML.
如果您还没有,您还需要spring-context
在您的应用程序 XML 中包含对类路径和上下文命名空间的依赖。
Reading this: http://www.mkyong.com/spring/spring-auto-scanning-components/might help
阅读此内容:http: //www.mkyong.com/spring/spring-auto-scanning-components/可能会有所帮助
回答by Kent
you didn't give enough information. which spring version? which application server?
你没有提供足够的信息。哪个春季版本?哪个应用服务器?
in general, you should have
一般来说,你应该有
<context:component-scan base-package="com.packagebase" />
in your spring xml conf files to use annotated beans.
在您的 spring xml conf 文件中使用带注释的 bean。
however, it won't always work.
然而,它并不总是有效。
I had problem with spring 2.5.6 + Jboss AS7. Jboss kept reporting annotated bean not defined. (NoSuchBeanDefinition or something like that). I switched to spring 3.0.0.Relase to resolve it.
我对 spring 2.5.6 + Jboss AS7 有问题。Jboss 一直报告未定义的带注释的 bean。(NoSuchBeanDefinition 或类似的东西)。我切换到 spring 3.0.0.Relase 来解决它。