接口
public interface Person { public void run(); public void eat(); public void write(); public void read();}
实现类
public class Student implements Person { @Override public void run() { System.out.println("Student is runing"); } @Override public void eat() { System.out.println("Student is eating"); } @Override public void write() { System.out.println("Student is writing"); } @Override public void read() { System.out.println("Student is reading"); }}
public class Teacher implements Person { @Override public void run() { System.out.println("Teacher is running"); } @Override public void eat() { System.out.println("Teacher is eating"); } @Override public void write() { System.out.println("Teacher is writing"); } @Override public void read() { System.out.println("Teacher is reading"); }}
启动器
/** * 控制反转:将创建哪个具体对象的控制权交到spring的xml文件中 * * 由主动行为变成了被动行为,即把创建对象交给了IoC容器处理,控制权颠倒过来了,这就是控制反转的由来 * * 依赖注入(DI)和控制反转(IoC)是从不同的角度描述的同一件事情,就是指通过引入IoC容器,利用依赖关系注入的方式,实现对象之间的解耦。 * * 控制权由应用代码中转到了外部容器,控制权的转移 * * @author darker * */public class PersonExample { public static void main(String[] args) { // Person p = new Student();// p.run(); // 读取配置文件(将配置文件中的bean加载进内存) ApplicationContext ctx = new ClassPathXmlApplicationContext("ioc.xml"); // 获取实例(区分大小写) Person teacher = (Person)ctx.getBean("IOCTeacher"); Person student = (Person)ctx.getBean("IOCStudent"); // 调用方法 teacher.read(); student.read(); }}
配置文件