【问题标题】:NoSuchBeanDefinitionException when bean is defined in XML在 XML 中定义 bean 时出现 NoSuchBeanDefinitionException
【发布时间】:2021-02-01 03:20:41
【问题描述】:

我正在尝试使用 @Resource 注释引用在 XML 文件中定义的 bean,但我不断收到 org.springframework.beans.factory.NoSuchBeanDefinitionException 异常。

这里是文件:

Employee.java:

public class Employee {
   private String name;
   private int age;

   //getter and setter methods
}

EmployeeManager.java:

@Service("employeeManager")
public class EmployeeManager {

   @Resource(name="employeeList")
   private List<Employee> employeeList;

   //other methods here
}

applicationContext.xml:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="
               http://www.springframework.org/schema/beans
               http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
    
    <bean id="employeeList" class="java.util.ArrayList">
        <constructor-arg>
            <list>
               <ref bean="bob" />
               <ref bean="sally" />
            </list>
        </constructor-arg>
    </bean>

    <bean id="bob" class="Employee">
        <property name="name" value="Bob"/>
        <property name="age" value="40"/>
    </bean>

    <bean id="sally" class="Employee">                    
        <property name="name" value="Sally"/>
        <property name="age" value="44"/>
    </bean>
    </beans>

理想情况下,我希望EmployeeManager.java 中的employeeList 变量被注入一个包含bob 和sally 的Employee 对象的List。当我运行我的应用程序时,我收到以下错误:

Error creating bean with name 'employeeManager': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'employeeList' available

我不确定我是否遗漏了什么,或者我的设置是否不正确。

【问题讨论】:

    标签: java xml spring javabeans code-injection


    【解决方案1】:

    您在 applicationContex.xml 中声明 bean 的语法是错误的。声明 BEAN 的语法是

    语法:

    <beans>
        <bean id="<beanReferenceName>" class="fullyQualifiedName of the class"/>
    </beans>
    

    鸡蛋:

    <beans>
        <bean id="transferService" class="com.acme.TransferServiceImpl"/>
    </beans>
    

    在 applicationContext.xml 中添加 Employee 类的完全限定名称

    【讨论】:

      猜你喜欢
      • 2018-08-31
      • 2018-02-04
      • 2015-08-27
      • 1970-01-01
      • 2019-05-20
      • 2017-10-10
      • 2018-05-25
      • 2017-10-09
      • 2015-04-17
      相关资源
      最近更新 更多