实例
假设我们拥有一个运行良好的Eclipse IDE,并采取以下步骤来创建一个Spring应用程序:
- 创建一个名称为SpringExample的项目,并在创建的项目的src文件夹下创建一个包com.jc2182
- 使用“添加外部JAR”选项添加所需的Spring库,如“Spring Hello World示例”一章中所述。
- 在com.jc2182包下创建Java类Student,Profile 和 MainApp。
- 在src文件夹下创建Beans配置文件Beans.xml。
- 最后一步是创建所有Java文件和Bean配置文件的内容,然后按以下说明运行应用程序。
以下是Profile.java内容。
package com.jc2182;
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() );
}
}
以下是Student.java的内容:
package com.jc2182;
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;
}
}
以下是MainApp.java文件的内容。
package com.jc2182;
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.jc2182.Profile"></bean>
<!-- Definition for student1 bean -->
<bean id = "student1" class = "com.jc2182.Student">
<property name = "name" value = "Zara" />
<property name = "age" value = "11"/>
</bean>
<!-- Definition for student2 bean -->
<bean id = "student2" class = "com.jc2182.Student">
<property name = "name" value = "Nuha" />
<property name = "age" value = "2"/>
</bean>
</beans>
创建完源和Bean配置文件后,让我们运行该应用程序。如果您的应用程序一切正常,这将打印以下消息:
Inside Profile constructor.
Age : 11
Name : Zara