前导:开始学习Spring核心思想,通过一个山寨精简版Spriing代码结合学习。
内容:1. 抽象BeanFactory-面向接口更易拓展BeanFactory-面向接口更易拓展。 2. 在AbstractBeanFactory内部初始化Bean。
这里的BeanDefinition相比上一个更加丰富,多了BeanDefinition包含的Bean的Class的信息,这里我们不在注册前就把Bean实例化给BeanDefinition,而是延迟到注册的时候才实例化Bean给BeanDefinition。
BeanDefinition:
package step2.core; public class BeanDefinition { private Object bean; private Class beanClass; private String beanClassName; public BeanDefinition() {} public Object getBean() { return bean; } public void setBean(Object bean) { this.bean = bean; } public Class getBeanClass() { return beanClass; } public void setBeanClass(Class beanClass) { this.beanClass = beanClass; } public String getBeanClassName() { return beanClassName; } public void setBeanClassName(String beanClassName) { this.beanClassName = beanClassName; try { this.beanClass = Class.forName(beanClassName); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
BeanFactory:
public interface BeanFactory { Object getBean(String name); void registerBeanDefinition(String name, BeanDefinition beanDefinition); }
AbstractBeanFactory:
public abstract class AbstractBeanFactory implements BeanFactory{ private Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<String, BeanDefinition>(); @Override public Object getBean(String name) { return beanDefinitionMap.get(name).getBean(); } @Override public void registerBeanDefinition(String name, BeanDefinition beanDefinition) { Object bean = doCreateBean(beanDefinition); beanDefinition.setBean(bean); beanDefinitionMap.put(name, beanDefinition); } /** * 初始化bean * @param beanDefinition * @return */ protected abstract Object doCreateBean(BeanDefinition beanDefinition); }
AutowireCapableBeanFactory:
public class AutowireCapableBeanFactory extends AbstractBeanFactory{ @Override protected Object doCreateBean(BeanDefinition beanDefinition) { try { Object bean = beanDefinition.getBeanClass().newInstance(); return bean; } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; } }
public class HelloWorldService { public void helloWorld(){ System.out.println("Hello World! from step2"); } }
public class BeanFactoryTest { @Test public void test() { // 1.初始化bean BeanFactory beanFactory = new AutowireCapableBeanFactory(); // 2.注入bean BeanDefinition beanDefinition = new BeanDefinition(); beanDefinition.setBeanClassName("step2.test.HelloWorldService"); beanFactory.registerBeanDefinition("helloWorldService", beanDefinition); // 3.获取bean HelloWorldService helloWorldService = (HelloWorldService)beanFactory.getBean("helloWorldService"); helloWorldService.helloWorld(); } }
时间: 2024-11-03 22:15:30