栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring基础学习之xml文件形式装配获取bean对象

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring基础学习之xml文件形式装配获取bean对象

1.首先导入依赖:
  
        org.springframework
        spring-context
        5.3.20
    
2.bean.xml文件编写:

获取文件头:Core Technologies

访问官网路径进行复制,这里已经帮你整理好了



文件全部内容:




    

    

3.两者不同方式读取bean.xml文件进行获取bean对象:
public class Client {
    
    
 * 核心容器的接口引发出的问题:
     * ApplicationContext:   单例对象适用  (常用)
     * 它在创建容器时,创建对象采取的策略是采用立即加载的方式,也就是说,只要一读取完配置文件马上就创建配置文件中配置的对象。
     * BeanFactory:         多例对象适用
     * 它在创建容器时,创建对象采取的策略是采用延迟加载的方式。也就是说,什么时候根据id获取对象了,什么时候才真正的创建对象。

    public static void main(String[] args) {

        //第一种加载方式:加载类任意路径下的配置文件
        System.out.println("第一种加载方式:加载类任意路径下的配置文件");
        ApplicationContext applicationContext = new FileSystemXmlApplicationContext("E:\Demo\demo02\demo01\src\main\resources\bean.xml");
        //根据id获取Bean对象
        AccountDao accountDao = (AccountDao) applicationContext.getBean("AccountDao");
        //  //.class获取AccountDao对象
        AccountDao accountDaoClass = applicationContext.getBean("AccountDao", AccountDao.class);
        IAccountService iAccountService = (IAccountService) applicationContext.getBean("IAccountService");
        System.out.println("AccountDao=" + accountDao + "n" + "IAccountService=" + iAccountService + "n" + "accountDaoClass=" + accountDaoClass);

        System.out.println("第二种加载方式:加载类路径下的配置文件");
        //第二种加载方式:加载类路径下的配置文件
        ApplicationContext applicationContext1 = new ClassPathXmlApplicationContext("bean.xml");
        //根据id获取Bean对象
        AccountDao accountDao1 = (AccountDao) applicationContext1.getBean("AccountDao");
        IAccountService iAccountService1 = (IAccountService) applicationContext.getBean("IAccountService");
        //.class获取IAccountService对象
        IAccountService IAccountServiceClass = applicationContext1.getBean("IAccountService", IAccountService.class);
        System.out.println("AccountDao1=" + accountDao1 + "n" + "iAccountService1=" + iAccountService1 + "n" + "IAccountServiceClass=" + IAccountServiceClass);




     System.out.println("--------------BeanFactory----------------");
        Resource resource = new ClassPathResource("bean.xml");
        BeanFactory beanFactory = new XmlBeanFactory(resource);
        IAccountService iAccountService = (IAccountService) beanFactory.getBean("IAccountService");
        System.out.println(iAccountService);

    }
}

到这里bean.xml文件装配bean获取对象到此完成,看看运行结果:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1020091.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号