其实 BeanFactory
已经提供了完整的功能,但是使用起来比较麻烦。现在用 ApplicationContext
做一个接口封装。
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()
用来初始化 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. 测试代码,比之前使用更佳简便,封装了实现细节。
@Test public void test() throws Exception { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("tinyioc.xml"); HelloWorldService helloWorldService = (HelloWorldService) applicationContext.getBean("helloWorldService"); helloWorldService.helloWorld(); }
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于