Spring框架学习 1、理解IOC //原始代码 public class Teacher { public String sayHello(){ return "Hello I am a teacher"; } } public class TestDemo { public static void main(String[] args) { Teacher teacher = new Teacher(); String message = teacher.sayHello(); System.out.println(message); } } //如何优化上述代码 public interface Person { public String sayHello(); } public class Teacher implements Person{ @Override public String sayHello(){ return "Hello I am a teacher"; } } public class TestDemo { public static void main(String[] args) { // Teacher teacher = new Teacher(); // String message = teacher.sayHello(); // System.out.println(message); //父接口的引用指向实现此接口的子类对象 Person person = new Teacher(); String str = person.sayHello(); System.out.println(str); } } //使用spring的方式 <?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="teacher" class="com.konjie.entity.Teacher"></bean> </beans> public class TestDemo { public static void main(String[] args) { // Teacher teacher = new Teacher(); // String message = teacher.sayHello(); // System.out.println(message); //父接口的引用指向实现此接口的子类对象 // Person person = new Teacher(); // String str = person.sayHello(); // System.out.println(str); //加载Spring的配置文件 ApplicationContext context = new ClassPathXmlApplicationContext ("spring-cfg.xml"); System.out.println(context); Teacher teacher = (Teacher) context.getBean("teacher"); System.out.println(teacher); String str = teacher.sayHello(); System.out.println(str); } }
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦