1.新建一个项目,java下新建包com.kuang.pojo,新建类Hello,在resource目录下新建配置文件beans.xml
配置Hello代码如下
package com.kuang.pojo;
public class Hello {
private String str;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
@Override
public String toString() {
return "Hello{" +
"str='" + str + ''' +
'}';
}
}
2.从Spring官网(Core Technologies (spring.io))获取xml代码
配置元数据
3.编写测试类MyTest
import com.kuang.pojo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
//获取Spring的上下文对象!
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//我们的对象现在都在Spring中的管理了,我们要使用,直接去里面取出来就可以!
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello.toString());
}
}
hello对象是由Spring创建的
hello对象的属性是由Spring容器设置的
这个过程叫做过程反转
现在,要实现不同的操作,只需要在xml配置文件中进行修改
IOC是思想,DI是这个思想的一种实现方式。IOC对象由 spring 创建 管理 装配
就相当于你请人吃饭
原来这套程序是:你写好菜单买好菜,客人来了自己把菜炒好招待
现在这套程序是:你告诉楼下餐厅,你要哪些菜,客人来的时候,餐厅把做好的你需要的菜送上来
此时的区别就是,如果我还需要做其他的菜,我不需要自己搞菜谱买材料再做好,而是告诉餐厅,我要什么菜,什么时候要,你做好送来
import com.kuang.dao.UserDaoMysqlImpl;
import com.kuang.service.UserService;
import com.kuang.service.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
//获取ApplicationContext:拿到Spring的容器
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//容器在手,天下我有,需要什么,就直接get什么!
UserServiceImpl userServiceImpl = (UserServiceImpl) context.getBean("UserServiceImpl");
userServiceImpl.getUser();
}
}



