当前位置: 首页 > 知识库问答 >
问题:

使用@组件定义bean并从XML读取列表时出错

易成天
2023-03-14

我必须说我是Spring的新手,所以很可能你们读这篇文章很容易。

我的例子很简单。我有类Main、Business和Client,为了从Business获取客户端,我创建了包含

我想做的是打印业务的客户端,但它抛给我以下错误:

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'clients': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public java.util.List com.springcourse.practice.Client.listClients; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.springcourse.practice.Client] found for dependency [collection of com.springcourse.practice.Client]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=arrayClients)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1116)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:626)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at com.springcourse.practice.Main.main(Main.java:9)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: public java.util.List com.springcourse.practice.Client.listClients; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.springcourse.practice.Client] found for dependency [collection of com.springcourse.practice.Client]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=arrayClients)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:514)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
    ... 13 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.springcourse.practice.Client] found for dependency [collection of com.springcourse.practice.Client]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=arrayClients)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:986)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:814)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)
    ... 15 more

下面是代码的内容

豆。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"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <context:component-scan base-package="com.springcourse.practice"></context:component-scan>

    <bean id="arrayClients" class="java.util.ArrayList">
        <constructor-arg>
            <list>
                <ref bean="firstClient"/>
                <ref bean="secondClient"/>
                <ref bean="thirdClient"/>
            </list>
        </constructor-arg>
    </bean>

    <bean id="firstClient" class="com.springcourse.practice.Client">
        <property name="name" value="Client Name 1"/>
        <property name="address" value="Somewhere 1"/>
    </bean>

    <bean id="secondClient" class="com.springcourse.practice.Client">
        <property name="name" value="Client Name 2"/>
        <property name="address" value="Somewhere 2"/>
    </bean>

    <bean id="thirdClient" class="com.springcourse.practice.Client">
        <property name="name" value="Client Name 3"/>
        <property name="address" value="Somewhere 3"/>
    </bean>

</beans>

客户界面

package com.springcourse.practice;

import java.util.List;

public interface ClientInterface {

    public List<Client> getClients();

}

客户端

package com.springcourse.practice;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component("clients")
public class Client implements ClientInterface {

    public String name;
    public String address;

    @Autowired
    @Qualifier("arrayClients")
    public List<Client> listClients;

    public List<Client> getClients(){
        return listClients;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

}

商务

package com.springcourse.practice;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

@Component("business")
public class Business {

    public String name = "Programmer City";

    public String getName() {
        return name;
    }

    public String getClients() {

        @SuppressWarnings("resource")
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("/beans.xml");
        Client clients  = (Client) context.getBean("clients");

        StringBuilder sb = new StringBuilder("The business name is: " + this.getName() + "\n");
        sb.append("The clients the business " + this.getName() + " has are: \n");       
        for(Client client: clients.getClients()) {
            sb.append("Client: " + client.name + " located in " + client.address + "\n");
        }

        return sb.toString();

    }

}

主要的

package com.springcourse.practice;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

    public static void main(String[] args) {

        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("/beans.xml");
        Business business  = (Business) context.getBean("business");
        System.out.println(business.getClients());
        context.close();


    }

}

谁能告诉我我做错了什么吗?如果有人想测试它,这里有一个项目链接:https://www.dropbox.com/s/isqahsxmxw8uxc1/Cap2_PracticeBusinessLocations_2.zip?dl=0

很难理解这些错误。非常感谢大家!

编辑bean。解决后的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"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <context:component-scan base-package="com.springcourse.practice"></context:component-scan>

    <bean id="arrayClients" class="java.util.ArrayList">
        <constructor-arg>
            <list>
                <ref bean="firstClient"/>
                <ref bean="secondClient"/>
                <ref bean="thirdClient"/>
            </list>
        </constructor-arg>
    </bean>

    <bean id="firstClient" class="com.springcourse.practice.Client">
        <property name="name" value="Client Name 1"/>
        <property name="address" value="Somewhere 1"/>
    </bean>

    <bean id="secondClient" class="com.springcourse.practice.Client">
        <property name="name" value="Client Name 2"/>
        <property name="address" value="Somewhere 2"/>
    </bean>

    <bean id="thirdClient" class="com.springcourse.practice.Client">
        <property name="name" value="Client Name 3"/>
        <property name="address" value="Somewhere 3"/>
    </bean>

    <bean id="arrayClientsTheSecond" class="java.util.ArrayList">
        <constructor-arg>
            <list>
                <ref bean="TheSecondfirstClient"/>
                <ref bean="TheSecondsecondClient"/>
                <ref bean="TheSecondthirdClient"/>
            </list>
        </constructor-arg>
    </bean>

    <bean id="TheSecondfirstClient" class="com.springcourse.practice.Client">
        <property name="name" value="Client Name 4"/>
        <property name="address" value="Somewhere 4"/>
    </bean>

    <bean id="TheSecondsecondClient" class="com.springcourse.practice.Client">
        <property name="name" value="Client Name 5"/>
        <property name="address" value="Somewhere 5"/>
    </bean>

    <bean id="TheSecondthirdClient" class="com.springcourse.practice.Client">
        <property name="name" value="Client Name 6"/>
        <property name="address" value="Somewhere 6"/>
    </bean>

</beans>

当我执行响应时是:

The business name is: Programmer City
The clients the business Programmer City has are: 
Client: Client Name 1 located in Somewhere 1
Client: Client Name 2 located in Somewhere 2
Client: Client Name 3 located in Somewhere 3
Client: Client Name 4 located in Somewhere 4
Client: Client Name 5 located in Somewhere 5
Client: Client Name 6 located in Somewhere 6

但是,这两个列表的名称不同,列表元素也不同。

共有1个答案

顾单弓
2023-03-14

虽然可以应用许多Java和Spring约定来改进代码(私有字段而不是公共字段、在bean方法中初始化新的ApplicationContext等),但我将重点讨论主要问题。

您可以简单地删除自动装配列表上的@Qualifier注释-Spring可以根据您的配置通过类型识别所需的bean。

此更改后代码有效。

 类似资料:
  • 6.4 Bean定义时使用表达式 无论XML还是注解类型的Bean定义都可以使用SpEL表达式。在两种方式下定义的表达式语法都是一样的,即:#{ } 6.4.1 XML类型的配置 Bean属性或者构造函数使用表达式的方式如下: <bean class="org.spring.samples.NumberGuess"> <property name="randomNumber" value=

  • 我在从xml文件中读取信息时遇到了一点问题... 传给我的文件有几千行。我只对300-400行感兴趣。当用户完成操作并且要读取的数据可以存储在中时,我不需要将任何数据写回xml。 我只对最内部名称元素的感兴趣(前两个是“098-0031”和“098-0032”)。 这是我的代码: 但是条件从来没有填满...谁能给我解释一下为什么。也许可以向我展示一种简单的方法来将这些值存储在中?提前感谢! 编辑:

  • 错误: 代码: 我需要插入完整的文件到setRuleSets方法,如何将FileInputStream帮助我在这里? 我应该通过读取fileinput流并将该文件路径传递给方法来重新创建临时文件吗?

  • 我在apache Spark中读取本地文件时出错。scala>val f=sc.textfile(“/home/cloudera/downloads/sample.txt”)

  • 我正在使用spring boot开发一个应用程序。我添加了一些具有xml配置的遗留依赖项库。我想使用Spring定义的豆子。xml文件。我已经在我的组件扫描中添加了这个包,但是这个bean似乎没有被提取出来。我应该为spring boot添加任何额外的配置来读取xml配置吗?

  • 我试图在RDD中将PostgreSQL 9.6中的一个表读取到Spark 2.1.1中,我在Scala中有以下代码。 但是,它返回以下错误: 组织。阿帕奇。火花SparkException:作业因阶段失败而中止:阶段1.0中的任务0失败4次,最近的失败:阶段1.0中的任务0.3丢失(TID 7,10.0.0.13,执行者1):组织。postgresql。util。PSQLException:列索引