1、直接得到 IOC 容器对象
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
封装起来:
1 public class ApplicationContextUtil { 2 private static ApplicationContext applicationContext = null; 3 public ApplicationContextUtil(){ 4 //无参构造器,可以不用写 5 } 6 7 static{ 8 applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); 9 } 10 11 public ApplicationContext getApplicationContext() { 12 return applicationContext; 13 }
使用时,直接用类名.方法调用即可:ApplicationContextUtil.ApplicationContextUtil();
2、通过工厂类得到 IOC 容器创建的对象
1 Resource resource = new ClassPathResource("applicationContext.xml"); 2 BeanFactory factory = new XmlBeanFactory(resource);
封装起来:
1 public class ApplicationContextFactoryUtil { 2 private static BeanFactory beanFactory = null; 3 public ApplicationContextFactoryUtil(){ 4 5 } 6 7 static{ 8 Resource resource = new ClassPathResource("applicationContext.xml"); 9 beanFactory = new XmlBeanFactory(resource); 10 } 11 12 public BeanFactory getBeanFactory() { 13 return beanFactory; 14 } 15 }
使用时,直接用类名.方法调用即可:ApplicationContextFactoryUti.getBeanFactory();
原创作者:DSHORE 作者主页:http://www.cnblogs.com/dshore123/ 原文出自:https://www.cnblogs.com/dshore123/p/11682126.html 欢迎转载,转载务必说明出处。(如果本文对您有帮助,可以点击一下右下角的 推荐,或评论,谢谢!) |
原文地址:https://www.cnblogs.com/dshore123/p/11682126.html
时间: 2024-10-02 23:09:32