IOC本质

一、IOC本质

IOC是一种思想,而依赖注入(DI)只是它的一种实现。

Spring过程:Spring容器在初始化时先读取配置文件,根据配置文件或元数据创建与组织对象存入容器中,程序使用时再从IOC容器中取出需要的对象。XML配置Bean时,Bean的定义信息和实现是分离的,而是采用注解的方式将两者合为一体,最新版的Spring已经可以零配置实现IOC,主要是因为Bean的定义信息以注解的形式定义在实现类中。

控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式,Spring中实现控制反转的是IOC容器,其实现方法是依赖注入(DI)。

二、IDEA快捷键

  • Alt+Insert:调用Genarate界面
  • Ctrl+Alt+v:自动补全变量
  • 快速缩写:psvm、sout、souf、serr、psf、psfi、psfs、toast

三、Hello Spring

1、在spring-study中创建一个模块,ArtifactId命名为"spring-02-hellospring",点击"src"——>"main"——>"java",创建一个"com.kuang.pojo"包,在包下创建一个Hello类,代码为:

package com.kuang.pojo;

public class Hello {
    private String str;

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }

    @Override
    public String toString() {
        return "Hello{" +
                "str='" + str + '\'' +
                '}';
    }

2、创建配置文件:

点击"src"——> "main"——> "resources",新建一个文件,命名为"beans.xml",文件中内容为:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

   <!-- 使用Spring创建对象,在Spring中这些都称为Bean
      在Java中,要想创建一个对象,一般为 类型 变量名 = new 类型();
      在SPring中,一个bean就相当于new 对象,其中id相当于变量名,
      class相当于对象(类型),property相当于给对象中的属性设值
   -->
    <bean id="hello" class="com.kuang.pojo.Hello">
        <property name="str" value="Spring" />
    </bean>

</beans>

上述代码中,只有<bean>标签是自己添加的,其他的都是在官网上(https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html)复制粘贴的。

3、创建测试文件

点击"src" ——>"test",新建一个MyTest类,代码内容为:

import com.kuang.pojo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args){
        //获取Spring的上下文对象
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //我们的对象都在Spring中管理,我们要想使用它们,就得从中调用
        Hello hello = (Hello) context.getBean("hello");
        System.out.println(hello.toString());
    }
}

4、运行MyTest,就可以看到输入:Hello{str='Spring'}

5、上述是一个简单的Spring程序,需要思考以下两个问题:

  • Hello对象是由谁创建的
  • Hello是由谁赋值的

6、练习:将spring-01-ioc1模块中更改为这种形式。

四、IOC创建对象的方式

1、默认使用无参构造创建对象

2、如何使用有参构造器创建对象?

  • 下标赋值
  • 类型匹配
  • 参数名

3、在配置文件加载的时候,容器中管理的对象就已经初始化了

五、Spring配置说明

1、别名(alias):对变量取别名

2、Bean配置:

  • 别名(alias):对变量取别名
  • Bean配置:1)id:bean的唯一标识符      2)class:bean对象所对应的全限定名   3)name:给id取别名,可以同时取多个别名,多个别名之间用空格、逗号、分号分隔
  • import:一般用于团队开发,可将多个配置文件导入合并为一个

猜你喜欢

转载自blog.csdn.net/buer219/article/details/103935379
ioc