IOC和DI

手动IOC

IOC指的是让spring容器创建对象,如果手动创建的话需要对要创建对象的类进行配置

创建一个User类

生成setget方法toString
无参构造方法
有参方法
spring容器创建对象的方式:
1、默认使用的无参构造创建对象: 必须要有无参构造法

package com.zhongruan.bean;

public class User {
    private int id;
    private String username;
    private String password;

    public User(int id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public User() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

配置文件

constructor-arg 当构造方法中有多个参数时,为参数进行注值
index 第几个位置 value 值
在这里插入图片描述

测试类

package com.zhongruan.test;

import com.zhongruan.bean.Student;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

/*
* @Component :用于一般实体类开发
* @Controller :分层开发中Controller
* @Service:分层开发中的Service层
* @Repository: 分层开发中的dao层
* */
@Component
public class Test1 {
    @Test
    public void test01() {
//    1、测试Spring容器的加载: 加载的时候,内部创建实例化对象
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext-annotation.xml");

        Student stu1 = (Student) context.getBean("stu1");
        System.out.println(stu1);
    }

}

自动IOC

IOC控制反转将对象交给Spring容器创建就需要添加注释支持
在这里插入图片描述
在要创建对象的类上添加注释

/*

  • @Component :用于一般实体类开发
  • @Controller :分层开发中Controller
  • @Service:分层开发中的Service层
  • @Repository: 分层开发中的dao层
  • */
    如果没有指定名字就是类名的第一个字母小写后的类名
    在这里插入图片描述

手动进行依赖注入

进行手动原来注入时要注入的类一定要生成set方法、
byName的原理:必须有set方法才能生效
1、对bean标签进行解析,遇到autowire="byName"的属性时,spring会自动找到类中的成员变量的set的方法。
2、找到set方法进行解析时,会先把set去掉,然后剩余单词首字母小写。
3、将小写后的单词拿到spring进行ID的匹配。
4、如果匹配成功,就将该标签所创建的进行依赖注入。
5、如果匹配失败,就会注入一个null值。
–>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值