1. 新建一個Spring項目
我將其命名爲SpringIoC
2. 右鍵src,新建一個Spring的配置文件,命名爲applicationContext.xml,暫時不進行配置
3. 在src下新建一個entity包,一個test包;entity包中包含實體類Student,test包中包含測試會用到的類TestStudent。文件目錄如下:
下面給出Student.java以及TestStudent.java的代碼
Student..java
public class Student {
private String stuNo;
private String stuName;
//省略getter and setter
//省略toString()
}
TestStudent.java
public class TestStudent {
public static void main(String[] args) {
//創建Spring的IoC容器對象
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
try{
Student student = (Student) applicationContext.getBean("student");
System.out.println(student.toString());
}catch (NoSuchBeanDefinitionException e)
{
System.out.println(e.getMessage());
System.out.println(e.getBeanName() + "不存在,請檢查配置文件");
}
}
}
在applicationContext.xml中配置Bean
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="student" class="entity.Student">
<property name="stuNo" value="2016211210069"></property>
<property name="stuName" value="iwaed"></property>
</bean>
</beans>
運行,結果如下:
done.