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.