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);
}
}
打开App,阅读手记