zoukankan      html  css  js  c++  java
  • @Qualifier注解详解

    @Qualifier注解意味着可以在被标注bean的字段上可以自动装配。Qualifier注解可以用来取消Spring不能取消的bean应用。

    下面的示例将会在Customer的person属性中自动装配person的值。

    1
    2
    3
    4
    5
    public class Customer
    {
        @Autowired
        private Person person;
    }

    下面我们要在配置文件中来配置Person类。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    <bean id="customer" class="com.howtodoinjava.common.Customer" />
     
    <bean id="personA" class="com.howtodoinjava.common.Person" >
        <property name="name" value="lokesh" />
    </bean>
     
    <bean id="personB" class="com.howtodoinjava.common.Person" >
        <property name="name" value="alex" />
    </bean>

    Spring会知道要自动装配哪个person bean么?不会的,但是运行上面的示例时,会抛出下面的异常:

    1
    2
    3
    Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException:
        No unique bean of type [com.howtodoinjava.common.Person] is defined:
            expected single matching bean but found 2: [personA, personB]

    要解决上面的问题,需要使用 @Quanlifier注解来告诉Spring容器要装配哪个bean:

    1
    2
    3
    4
    5
    6
    public class Customer
    {
        @Autowired
        @Qualifier("personA")
        private Person person;
    }
  • 相关阅读:
    Spring boot 请求接口404
    Windows下安装Redis
    利用maven的profiles灵活的配置多环境
    各个JSON技术的比较
    常用工具软件
    Java方法 传值方式
    JVM内存模型
    spring-task解决定时问题
    quartz Cron表达式解读
    maven 常用命令
  • 原文地址:https://www.cnblogs.com/wirr/p/8487113.html
Copyright © 2011-2022 走看看