亲宝软件园·资讯

展开

Spring创建IOC容器的方式解析

人气:0

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

您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论