有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java没有名为“…”的bean已定义和Spring@Resource注释

我使用@Resource注释bean类,@Autowired注释Autowired依赖项, 在Spring配置文件中,这些东西:

^{pr1}$

因此,它工作良好(经过测试)。Spring使用@Resource注释扫描package1、package2和类 然后,如果从控制台应用程序(比如,使用main()函数)进行测试,我可以使用getBean()获取它们

但当我尝试使用下一种方法(在容器管理的环境中使用Spring=with 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

那我看到了什么?我无法获取任何@Resource注释的bean
Spring根本找不到它们
我仍然可以获取bean中显式存在的getBean()bean。xml


问题出在哪里


共 (2) 个答案

  1. # 1 楼答案

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

  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" />