• Spring(四)——Spring容器加载的三种方式讲解


    一、类路径获得配置文件

    后面的路径放到src路径下的相对地址。

    代码打包会把src打包到class路径下,类路径,就是相对src的路径。

    二、文件系统路径获得配置文件

    三、使用BeanFactory

    四、案例代码

     1 package com.gyf.test;
     2 
     3 import com.gyf.service.IUserService;
     4 
     5 import org.junit.Test;
     6 import org.springframework.beans.factory.BeanFactory;
     7 import org.springframework.beans.factory.xml.XmlBeanFactory;
     8 import org.springframework.context.ApplicationContext;
     9 import org.springframework.context.support.ClassPathXmlApplicationContext;
    10 import org.springframework.context.support.FileSystemXmlApplicationContext;
    11 import org.springframework.core.io.FileSystemResource;
    12 
    13 public class Lesson01 {
    14     @Test
    15     public void test1(){
    16         //Spring容器加载有3种方式
    17         //第一种:使用类路径获得配置文件,ClassPathXmlApplicationContext
    18         ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    19         IUserService userService = (IUserService) context.getBean("userService");
    20         userService.add();
    21 
    22         //第二种方式:使用文件系统路径获得配置文件,FileSystemXmlApplicationContext
    23         ApplicationContext context1 =
    24                 new FileSystemXmlApplicationContext("D:\2018WorkSpaceXXY\IDEA\day02_Spring_20200825\src\beans.xml");
    25         IUserService userService1 = (IUserService) context1.getBean("userService");
    26         userService1.add();
    27 
    28         //第三种方式:使用BeanFactory
    29         String path = "D:\2018WorkSpaceXXY\IDEA\day02_Spring_20200825\src\beans.xml";
    30         BeanFactory factory = new XmlBeanFactory(new FileSystemResource(path));
    31         IUserService userService2 = (IUserService) factory.getBean("userService");
    32         userService2.add();
    33     }
    34 }
    View Code

    五、Spring内部创建对象的原理

    1. 解析XML文件,获取类名,id,属性。

    2. 通过反射,用类名创建对象

    3. 给创建的对象赋值

  • 相关阅读:
    MyBatis3-实现多表关联数据的查询
    MyBatis3-实现单表数据的增删查改
    MyBatis3-以接口方式编程
    如何识别人的技术能力和水平?
    评审的艺术——谈谈现实中的代码评审 专题
    Spring编程式和声明式事务实例讲解
    Spring Webflux: Kotlin DSL [片断]
    Spring3.1 对Bean Validation规范的新支持(方法级别验证)
    Android setImageResource与setImageBitmap的区别
    Android开发中,9-patch (九宫格)图片作为背景带来的问题
  • 原文地址:https://www.cnblogs.com/upyang/p/13562450.html
Copyright © 2020-2023  润新知