其實(shí)BeanFactory
已經(jīng)提供了完整的功能尘分,但是使用起來(lái)比較麻煩∪褂蹋現(xiàn)在用ApplicationContext
做一個(gè)借口封裝员凝。
1. ApplicationContext
接口
public interface ApplicationContext extends BeanFactory {
}
2. AbstractApplicationContext
抽象類
public abstract class AbstractApplicationContext implements ApplicationContext {
protected AbstractBeanFactory beanFactory;
public AbstractApplicationContext(AbstractBeanFactory beanFactory) {
this.beanFactory = beanFactory;
}
public void refresh() throws Exception{
}
@Override
public Object getBean(String name) throws Exception {
return beanFactory.getBean(name);
}
}
3. ClassPathXmlApplicationContext
xml的ApplicationContext摇锋,refesh()
用來(lái)初始化Bean
public class ClassPathXmlApplicationContext extends AbstractApplicationContext {
private String configLocation;
public ClassPathXmlApplicationContext(String configLocation) throws Exception {
this(configLocation, new AutowireCapableBeanFactory());
}
public ClassPathXmlApplicationContext(String configLocation, AbstractBeanFactory beanFactory) throws Exception {
super(beanFactory);
this.configLocation = configLocation;
refresh();
}
@Override
public void refresh() throws Exception {
XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(new ResourceLoader());
xmlBeanDefinitionReader.loadBeanDefinitions(configLocation);
for (Map.Entry<String, BeanDefinition> beanDefinitionEntry : xmlBeanDefinitionReader.getRegistry().entrySet()) {
beanFactory.registerBeanDefinition(beanDefinitionEntry.getKey(), beanDefinitionEntry.getValue());
}
}
}
4. 測(cè)試代碼苇侵,比之前使用更佳簡(jiǎn)便油狂,封裝了實(shí)現(xiàn)細(xì)節(jié)历恐。
@Test
public void test() throws Exception {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("tinyioc.xml");
HelloWorldService helloWorldService = (HelloWorldService) applicationContext.getBean("helloWorldService");
helloWorldService.helloWorld();
}