美文网首页工作生活
Spring的@Qualifier注解(搭配@AutoWired

Spring的@Qualifier注解(搭配@AutoWired

作者: 安在成丶 | 来源:发表于2019-07-04 09:49 被阅读0次

Spring @Qualifier 注释的作用在于,当创建了多个相同类型的Bean时,并且只想用其中一个指定的bean来装配属性的时候,就可以使用@Qualifier和@AutoWired搭配注解。

这两个组合注解,可以指定一个真正的bean为属性注入依赖,通过“byName”的形式,从而消除多个bean自动装配造成的混乱。

也就是通过指定名称,去匹配Spring容器中具有相同名称的Bean。

Student.java中内容如下:

@Autowired

@Qualifier("student1")

private Student student;

ApplicationContext.xml中内容如下:

<bean id="student1" class="com.tutorialspoint.Student">

<property name="name" value="Zara" />

<property name="age" value="11"/> </bean>

<bean id="student2" class="com.tutorialspoint.Student">

<property name="name" value="Nuha" />

<property name="age" value="2"/> </bean>

如果按照上述方式指定名称注入,则会为student属性,注入名为Student1的bean的属性值。

相关文章

网友评论

    本文标题:Spring的@Qualifier注解(搭配@AutoWired

    本文链接:https://www.haomeiwen.com/subject/lasthctx.html