package com.Dao;
public interface testDao {
public void sayhello();
}
package com.Dao;
public class testDaoImpl implements testDao{
@Override
public void sayhello() {
System.out.println("这是一个hello方法");
}
}
3.配置文件添加如下语句
4.测试类
注意:目前有两种参数通过getBean获取对象
- id的方式创建的对象与直接用字节码创建的对象地址是一样的多次在配置文件中用不同的id声明同一个类会报错
package com.Test;
import com.Dao.testDaoImpl;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class test {
public static void main(String[] args) {
//激活配置
ClassPathXmlApplicationContext test = new ClassPathXmlApplicationContext("spring-config.xml");
testDaoImpl testDao = (testDaoImpl) test.getBean("test");
testDao.sayhello();
testDaoImpl testDao1 = test.getBean(testDaoImpl.class);
testDao1.sayhello();
//进行比较是否为同一地址
testDaoImpl testDao2 = (testDaoImpl) test.getBean("test");
System.out.println(testDao==testDao1);
System.out.println(testDao1==testDao2);
System.out.println(testDao==testDao2);
//运行结果
// 这是一个hello方法
// 这是一个hello方法
// true
// true
// true
}
}
5.IOC的原理
- 测试类:找到构造器ClassPathXmlApplicationContext,解析xml文件xml文件:解析到标签后将class通过反射进行对象创建再保存到内部的容器中。测试类:当测试类使用getBean方法时,从容器中返回这个对象
注意:在配置文件中声明有参数的对象,实体类必须依赖setget方法
Stdent类
package com.Dao;
public class Student {
private int id;
private String name;
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;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + ''' +
'}';
}
}
配置文件
测试类:
package com.Test;
import com.Dao.Student;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class test01 {
public static void main(String[] args) {
ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("spring-config.xml");
Student student = (Student) classPathXmlApplicationContext.getBean("std");
System.out.println(student.toString());
}
}



