wirr

@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;
}

分类:

技术点:

相关文章:

  • 2021-11-17
  • 2021-11-19
  • 2021-06-30
  • 2021-10-01
  • 2021-09-11
  • 2018-02-28
  • 2019-12-02
  • 2021-11-19
猜你喜欢
  • 2020-05-03
  • 2021-12-31
  • 2022-01-07
  • 2019-12-30
  • 2021-11-08
  • 2020-06-10
  • 2020-10-11
相关资源
相似解决方案