1、直接得到 IOC 容器对象 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); 封装起来: public class ApplicationContextUtil { private static ApplicationContext applicationConte
1、直接得到 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();
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自由互联。