實現原理
採用XML方式配置Bean的時候,Bean的定義和實現分離的,採用註解的方式可以將兩者合為一體,Bean的定義資訊直接以註解形式定義在實現類中,從而實現了零配置。
控制反轉是一種通過描述(XML/註解),並通過第三方去生產或獲取特定物件的方式,Spring中實現控制反轉的是IoC容器,其實現方法為依賴注入(Dependency Injection,DI)。
- 建立一個普通Maven專案
- 匯入Maven依賴(見前章)
- 編寫一個實體類
package cn.iris.pojo;
/**
* @author Iris 2021/8/10
*/
public class HelloSpring {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "HelloSpring{" +
"name='" + name + '\'' +
'}';
}
}
- 編寫【配置檔案】
<?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-->
<bean id="hello" class="cn.iris.pojo.HelloSpring">
<property name="name" value="Spring"/>
</bean>
</beans>
- 例項化容器&測試
import cn.iris.pojo.HelloSpring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author Iris 2021/8/10
*/
public class MyTest {
public static void main(String[] args) {
// 獲取Spring的上下文物件
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
// 物件均在Spring中管理,使用時從中取出
Object hello = (HelloSpring) context.getBean("hello");
System.out.println(hello.toString());
}
}
//輸出結果
HelloSpring{name='Spring'}
HelloSpring物件由【Spring建立】
HelloSpring的屬性由【Spring容器設定】
控制反轉(IoC)
控制:使用Spring時,物件由Spring建立
反轉:程式本身不建立物件,變成被動的接受
IoC即是將主動的建立變為被動的接收ontext
到現在,我們徹底不用去程式中改動,實現不同操作僅需在xml配置檔案中進行修改-->IoC:物件由Spring來建立、管理、裝配
程式設計師寫好程式,告訴Spring寫到‘單子’上,使用者照著‘單子’去拿自己想用的
<!--使用Spring建立物件,Spring中將物件描述為Bean
bean = new 型別()
id = 變數名
class = new 的物件
property 給物件屬性設值
name 屬性名
value 普通型別賦值
ref 引用型別賦值
-->
IoC建立物件方式
- 使用無參構造建立物件【預設】
- 使用有參構造建立物件【Spring提供方法(基於實體類中的有參構造實現)】
- 根據下標賦值(從0開始)
<bean class="cn.iris.pojo.User" id="user">
<!--1. 下標賦值(從0開始)-->
<constructor-arg index="0" value="Iris"/>
</bean>
- 根據型別賦值(不建議使用)
<!--2. 根據引數型別比對賦值-->
<constructor-arg type="java.lang.String" value="iris"/>
- 根據引數名賦值
<!--3. 根據引數名賦值-->
<constructor-arg name="name" value="iris"/>