发表于: 2017-10-22 22:42:31
2 576
今天学习的内容:
控制反转的一个简单的例子:
在eclipse中创建如图所示的一个项目:
引入相应的jar包,放在lib文件夹下:
新建ApplicationContext.xml文件
创建一个学校类:
package com.hpe.bean;
public class School {
/*
* 学校类
* */
private String name;
public School(String name) {
this.name=name;
}
public void printInfo() {
System.out.println("该学校的名称是:"+name);
}
}
创建一个学生类:
package com.hpe.bean;
public class Student {
/*
* 学生类
* */
public int id;
public String name;
private School school;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public School getSchool() {
return school;
}
public void setSchool(School school) {
this.school = school;
}
}
在appliactionContext.xml里的配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<!-- 引入bean的约束-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<bean id="school" class="com.hpe.bean.School">
<constructor-arg index="0">
<value>郑州财经政法大学</value>
</constructor-arg>
</bean>
<bean id="student" class="com.hpe.bean.Student">
<property name="id" value="001"/>
<property name="name" value="昭君"/>
<property name="school" ref ="school"/>
</bean>
</beans>
创建测试类:
package com.hpe.test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.hpe.bean.Student;
public class Client {
public static void main(String[] args) {
// TODO Auto-generated method stub
BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
Student student=(Student)factory.getBean("student");
System.out.println("该学生的名字是:"+student.getName());
student.getSchool().printInfo();
}
}
结果:
问题:
在运行代码的时候出现找不到类的错误,发现类的路径写错了。改正之后又有一个错误
ClassPathXmlApplicationContext("applicationContext.xml")的类型不对,必须要强转,然后删了引入的包,发现是BeanFactory的包引入错误。
明天继续学习关于Spring的内容。
评论