手动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值。
–>