Spring IOC

一、Spring IOC的理解
  • IOC(Inversion of Control,控制反转)是Spring框架的核心思想之一,其主要作用是解耦。IOC是指将创建对象的控制权移交给Spring框架进行管理,由Spring框架通过配置文件或注解的方式创建Bean对象,管理各个bean对象之间的依赖关系,让各个对象之间的耦合性降低,实现解耦。
    • 控制:创建对象的权利
    • 反转:将权利移交给外部环境(Spring框架、IOC容器)

  • IOC是高内聚、低耦合的编程思想
  • 硬编码实现解耦:
    • 1.不需要new对象,通过反射创建;
    • 2.将需要创建的对象独立保存在资源文件中,动态加载
二、解耦的方法

方法一:Beans.properties(key=value)==>BeansFactory(getbean()==>new properties(创建工具类)==>加载文件==>获取value)==>实体类调用getbean方法==>test(获取对象)

1.在resources中创建配置文件Beans.properties

Properties继承了Hashtable 类,以Map 的形式进行放置值,put(key,value) 和 get(key)。

Properties 类表示了一个持久的属性集。Properties 可保存在流中或从流中加载。属性列表中每个键及其对应值都是一个字符串。

Properties 文件内容的格式是:键=值 形式,Key值不能够重复。

找到需要以解耦方式获取实例对象的类,在配置文件中写出key=实例对象类

2.创建一个工厂BeansFactory

自定义一个getBean方法

//传入key,根据key找到value,即所对应的需要创建的实例对象
public Object getBean(String key){}

按照用户需求以解耦的方式创建对象

  • 1.创建工具类
Properties properties = new Properties();
  • 2.加载文件 
    • 从当前的类加载器的getClassLoader().getResourcesAsStream来获取
    • load ( InputStream inStream): 从输入流中读取属性列表(键和元素对)。
InputStream inputStream = test01.class.getClassLoader().getResourceAsStream("Beans.properties");
properties.load(inputStream);
  • 3.通过key获取value 
  • getProperty ( String key): 用指定的键在此属性列表中搜索属性。也就是通过参数 key ,得到 key 所对应的 value。
  • 通过 Class 类的newInstance() 方法创建对象
String classPath = properties.getProperty(key);
return Class.forName(classPath).newInstance();

3.在实体类Student中调用getBean方法,传入key,获取对象

jason stu=(jason)BeansFactory.getBean("stuname");

4.在测试类获取对象

Student student = new Student();

方法二:pom.xml(坐标)==>Spring Config(注入类)==>test(获取Spring容器==>获取对象)

采用Spring IOC解耦

1.Spring环境的搭建

  • 在pom.xml中写出坐标
<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.3.27</version>
    </dependency>
</dependencies>
    • 在resources中创建配置文件Spring Config

2.Spring IOC

1.找到需要以解耦方式获取实例对象的类

2.将需要spring管理的类注入spring容器(配置文件中 beans.xml)

<bean id="唯一标识" class="类"></bean>

<!--注入类 -->
<bean id="student" class="com.apesourse.pojo.Student"></bean>

3.向spring容器中索取java实例(解耦)(测试类)

3.1.加载spring核心配置文件,获取spring容器对象

ApplicationContext applicationContext=new ClassPathXmlApplicationContext("beans.xml");

BeanFactory(父)

ApplicationContext(子)

ClassPathXmlApplicationContext===>通过加载主配置文件的相对路径,获取spring容器FileSystemXmlApplicationContext===>通过加载主配置文件的绝对路径,获取spring容器AnnotationConfigApplicationContext===>加载配置类,获取spring容器

3.2.获取对象

Student student = (Student) applicationContext.getBean("student");
System.out.println(student);

  • 27
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值