Spring创建IOC容器的方式解析

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Spring创建IOC容器的方式解析

  2021-04-02 我要评论

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();

您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们