Spring创建IOC容器的方式解析
人气:01、直接得到 IOC 容器对象
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
封装起来:
public class ApplicationContextUtil { private static ApplicationContext applicationContext = null; public ApplicationContextUtil(){ //无参构造器,可以不用写 } static{ applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); } public ApplicationContext getApplicationContext() { return applicationContext; }
使用时,直接用类名.方法调用即可:ApplicationContextUtil.ApplicationContextUtil();
2、通过工厂类得到 IOC 容器创建的对象
Resource resource = new ClassPathResource("applicationContext.xml"); BeanFactory factory = new XmlBeanFactory(resource);
封装起来:
public class ApplicationContextFactoryUtil { private static BeanFactory beanFactory = null; public ApplicationContextFactoryUtil(){ } static{ Resource resource = new ClassPathResource("applicationContext.xml"); beanFactory = new XmlBeanFactory(resource); } public BeanFactory getBeanFactory() { return beanFactory; } }
使用时,直接用类名.方法调用即可:ApplicationContextFactoryUti.getBeanFactory();
您可能感兴趣的文章:
加载全部内容