获取Spring的IOC容器对象的方式

获取Spring的IOC容器对象的方式

从下面的类图中可以看出,ApplicationContext接口有很多的实现类,我们一般用到的是
ClassPathXmlApplicationContext、FileSystemXmlApplicationContext、AnnotationConfigApplicationContext这3个实现类,通过这3个实现类我们可以获取到Spring的IOC容器对象。
在这里插入图片描述

ClassPathXmlApplicationContext

ClassPathXmlApplicationContext用于在类路径下加载配置文件。

 public void test1() {
       
       ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:bean.xml");
        AccountService accountService = (AccountService) applicationContext.getBean("accountService");
        System.out.println("accountService" + accountService);
        AccountDaoImpl accountDao = applicationContext.getBean(AccountDaoImpl.class);
        System.out.println("accountDao" + accountDao);
       
    }

FileSystemXmlApplicationContext

FileSystemXmlApplicationContext用于在任意路径下加载配置文件。

    @Test
    public void test2() {

        ApplicationContext ac = new FileSystemXmlApplicationContext("C:\\Users\\DELL\\Desktop\\bean.xml");
        AccountService accountService = (AccountService) ac.getBean("accountService");
        System.out.println("accountService" + accountService);

        AccountDaoImpl accountDao = ac.getBean(AccountDaoImpl.class);
        System.out.println("accountDao" + accountDao);
    }

AnnotationConfigApplicationContext

AnnotationConfigApplicationContext用于读取注解。

总结

这个3种方式用的比较多的是第一种和第3种,第二种一般用的不多,因为配置文件随便乱放会造成问题;

核心容器的两个接口

ApplicationContext

在构建核心容器对象时,采用的是立即加载的方式,也就是说只要一读取配置文件就创建配置文件中的对象。

BeanFactory

在构建核心容器对象时,采用的是延迟加载的方式,也就是说什么时候获取对象了,什么时候才创建对象。

    @Test
    public void test3() {
        Resource resource = new ClassPathResource("classpath:bean.xml");;
        BeanFactory beanFactory = new XmlBeanFactory(resource);

        AccountService accountService = (AccountService)beanFactory.getBean("accountService");
    }

参考

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值