代码目录结构
small-spring-step-01
└── src
├── main
│ └── java
│ └── cn.bugstack.springframework
│ ├── BeanDefinition.java
│ └── BeanFactory.java
└── test
└── java
└── cn.bugstack.springframework.test
├── bean
│ └── UserService.java
└── ApiTest.java
定义BeanDefinition
用一个Object存放Bean对象
public class BeanDefinition {
private Object bean;
public BeanDefinition(Object bean) {
this.bean = bean;
}
public Object getBean() {
return bean;
}
}
定义Bean工厂
包括Bean的注册和获取操作
public class BeanFactory {
private Map<String, BeanDefinition>
beanDefinitionMap = new ConcurrentHashMap<>();
public Object getBean(String name) {
return beanDefinitionMap.get(name).getBean();
}
public void registerBeanDefinition(String name, BeanDefinition beanDefinition)
{
beanDefinitionMap.put(name, beanDefinition);
}
}
测试
定义了一个 UserService 对象
public class UserService {
public void queryUserInfo(){
System.out.println("查询用户信息");
}
}
测试用例
@Test
public void test_BeanFactory(){
// 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();
}
成功初始化Bean工厂, 注册Bean, 获取Bean, 这样就实现了一个最简单的Bean容器
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/282330.html