可能会有这样一种情况,当你创建多个具有相同类型的 bean 时,并且想要用一个属性只为它们其中的一个进行装配,在这种情况下,你可以使用 @qualifier 注释和 @autowired 注释通过指定哪一个真正的 bean 将会被装配来消除混乱。下面显示的是使用 @qualifier 注释的一个示例。
让我们使 eclipse ide 处于工作状态,请按照下列步骤创建一个 spring 应用程序:
步骤 | 描述 |
---|---|
1 | 创建一个名为 springexample 的项目,并且在所创建项目的 src 文件夹下创建一个名为 com.tutorialspoint 的包。 |
2 | 使用 add external jars 选项添加所需的 spring 库文件,就如在 spring hello world example 章节中解释的那样。 |
3 | 在 com.tutorialspoint 包下创建 java 类 student,profile 和 mainapp。 |
4 | 在 src 文件夹下创建 beans 配置文件 beans.xml。 |
5 | 最后一步是创建所有 java 文件和 bean 配置文件的内容,并且按如下解释的那样运行应用程序。 |
这里是 student.java 文件的内容:
package com.tutorialspoint;
public class student {
private integer age;
private string name;
public void setage(integer age) {
this.age = age;
}
public integer getage() {
return age;
}
public void setname(string name) {
this.name = name;
}
public string getname() {
return name;
}
}
这里是 profile.java 文件的内容:
package com.tutorialspoint;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.beans.factory.annotation.qualifier;
public class profile {
@autowired
@qualifier("student1")
private student student;
public profile(){
system.out.println("inside profile constructor." );
}
public void printage() {
system.out.println("age : " + student.getage() );
}
public void printname() {
system.out.println("name : " + student.getname() );
}
}
下面是 mainapp.java 文件的内容:
package com.tutorialspoint;
import org.springframework.context.applicationcontext;
import org.springframework.context.support.classpathxmlapplicationcontext;
public class mainapp {
public static void main(string[] args) {
applicationcontext context = new classpathxmlapplicationcontext("beans.xml");
profile profile = (profile) context.getbean("profile");
profile.printage();
profile.printname();
}
}
考虑下面配置文件 beans.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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config/>
<!-- definition for profile bean -->
<bean id="profile" class="com.tutorialspoint.profile">
</bean>
<!-- definition for student1 bean -->
<bean id="student1" class="com.tutorialspoint.student">
<property name="name" value="zara" />
<property name="age" value="11"/>
</bean>
<!-- definition for student2 bean -->
<bean id="student2" class="com.tutorialspoint.student">
<property name="name" value="nuha" />
<property name="age" value="2"/>
</bean>
</beans>
一旦你在源文件和 bean 配置文件中完成了上面两处改变,让我们运行一下应用程序。如果你的应用程序一切都正常的话,这将会输出以下消息:
inside profile constructor.
age : 11
name : zara