没有名为“...”的bean被定义和Spring @Resource注释

3
我使用@Resource来注释bean类,@Autowired来自动装配依赖项,在Spring配置文件中添加以下内容:
    context:component-scan base-package="package1,package2" 
    tx:annotation-driven
所以,它可以正常工作(已测试)。Spring扫描带有@Resource注释的package1、package2类,然后我可以使用getBean()从控制台应用程序中获取它们(例如,使用main()函数)。但是当我尝试使用下一个方法(在Tomcat中使用Spring容器管理环境)时:
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:beans.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
编译一个包含所有bean类的jar,并将此jar放入WEB-INF/lib中。那么我看到了什么?我无法getBean()任何那些@Resource注释的bean!Spring无法找到它们。但是我仍然可以getBean()明确存在于beans.xml中的bean。问题出在哪里呢?

请您重新格式化第一段代码片段好吗? - lexicore
2个回答

2
缺少了 <context:annotation-config/> 标签吗?
<context:annotation-config/>    
<context:component-scan base-package="package1"/>
<context:component-scan base-package="package2"/>
<tx:annotation-driven transaction-manager="transactionManager" />

or 

<context:annotation-config/>    
<context:component-scan base-package="package1, package2"/>
<tx:annotation-driven transaction-manager="transactionManager" />

0
我不确定独立模式下它是如何工作的,但是您Spring上下文中的""元素允许使用“@Resource”注释。请查看Spring文档以获取更多信息。

@David M. Karr,你说你不确定是什么意思?我测试过这个东西,在独立模式下它运行良好,问题在于Web应用程序和Spring之间的协调。 - EugeneP
1
我说我不确定它在独立运行时如何工作,因为我看到的与您的配置有关的问题,在独立应用程序和Web应用程序中都无法解决。我还注意到,我试图提供的关键信息被省略了,因为我没有转义尖括号。您需要拥有“context:annotation-config”元素。 - David M. Karr

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