没有定义名为'...'的bean和Spring @Resource注释

时间:2010-04-14 14:53:04

标签: java spring tomcat servlets

我使用@Resource来注释bean类,@ Autowired来自动连接依赖项, 并在Spring配置文件中:

    context:component-scan base-package="package1,package2" 
    tx:annotation-driven

所以,它工作正常(测试)。 Spring使用@Resource注释扫描package1,package2,类 然后我可以使用getBean()获取它们如果从CONSOLE APPLICATION中测试[例如,使用main()函数]。

但是当我尝试使用下一种方法时(在容器托管环境中使用Spring =使用Tomcat):

    <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!
春天根本找不到它们 我仍然可以获得beans.xml中明确存在的getBean()bean

问题出在哪里?

2 个答案:

答案 0 :(得分: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" />

答案 1 :(得分:0)

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