IOC控制反转的理解与实现
1.IOC控制反转的一个简单原理
注:这篇文章仅是我个人的一个观点
1.就是他实现了解耦,实现了高内聚低耦合的一个思想,把控制权交给用户而不是程序本身。
2.spring的实现IOC控制反转是谁控制对象的创建,传统应用程序是由程序本身进行创建的,使用spring后,对象是有spring来进行创建。
依赖注入:就是利用set方法进行注入的.
IOC:IOC其实就是一种编程是思想,有主动的编程变成被动的接受。
3.
4.
4.引入Spring官方的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!--
注:此头部禁止修改,可以去spring官网中文文档进行查找
https://www.docs4dev.com/docs/zh/spring-framework/5.1.3.RELEASE/reference/
-->
<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
http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
5.引入spring并开始进行反转(例子)
注:value是静态赋值,ref是动态赋值,也就是说ref是对应的是一个实现类。
<?xml version="1.0" encoding="UTF-8"?>
<!--
注:此头部禁止修改,可以去spring官网中文文档进行查找
https://www.docs4dev.com/docs/zh/spring-framework/5.1.3.RELEASE/reference/
-->
<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
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--
id = 变量名字
class = 是你要new的类的全路径
property = 属性
name = 相当于键值对的形式,name则是键
value = 值
-->
<bean id="tset" class="com.zzy.pojo.TestBean">
<property name="name" value="叼叼叼">
</property>
</bean>
</beans>
2.实现Spring的IOC例子的控制反转
1.给创建一个bean
package com.zzy.pojo;
public class TBean {
private String test;
//给他应该无参无返回的一个输出。
public TBean() {
System.out.println("我是无参构造");
}
//给一个get和set的方法
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
//写一个show的方法方便xml用ref进行动态赋值
public void show(){
System.out.println("我是show"+test);
}
//如果在xml里面进行value 需要生成一个tostring的
@Override
public String toString() {
return "TBean{" +
"test='" + test + '\'' +
'}';
}
}
2.配置xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
注:此头部禁止修改,可以去spring官网中文文档进行查找
https://www.docs4dev.com/docs/zh/spring-framework/5.1.3.RELEASE/reference/
-->
<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
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="show" class="com.zzy.pojo.TBean"></bean>
<bean id="tBean" class="com.zzy.pojo.TBean">
<property name="test" ref="show"></property>
</bean>
</beans>
3.写一个测试类
public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
TBean test = (TBean) context.getBean("tBean");
System.out.println(test.toString());
}
}

浙公网安备 33010602011771号