快速手写Spring框架的IOC笔记(1)
快速手写Spring框架的IOC(1)
1. 快速事项一个简单的bean容器
(1)用来装配bean的容器
public class BeanDefinition {
private Object beanName;
public BeanDefinition(Object beanName) {
this.beanName= beanName;
}
public Object getBeanName() {
return beanName;
}
}
(2)
public class BeanFactory {
private Map<String, BeanDefinition> bDMap = new ConcurrentHashMap<>();
public Object getBean(String name) {
return bDMap.get(name).getBean();
}
public void registerBeanDefinition(String name, BeanDefinition beanDefinition) {
bDMap.put(name, beanDefinition);
}
}
(3)测试类UserService
public class UserService {
public void UserInfo(){
System.out.println("成功的获取bean");
}
}
(4)测试方法
public class TestBean{
@Test
public void test(){
// 1.初始化 BeanFactory
BeanFactory beanFactory = new BeanFactory();
// 2.注册 bean
BeanDefinition beanDefinition = new BeanDefinition(new UserService());
beanFactory.registerBeanDefinition("userService", beanDefinition);
// 3.获取 bean
UserService userService = (UserService) beanFactory.getBean("userService");
userService.queryUserInfo();
}
}