1. 程式人生 > 其它 >Spring框架之IoC( Inversion of Control )基礎知識入門

Spring框架之IoC( Inversion of Control )基礎知識入門

1、IoC建立物件的方式

  1. 使用無參構造建立物件

  2. 假如要使用有參構造建立:

    1. 下標賦值constructor-arg

      <!--有參-->
      <bean id="User" class="com.reliable.pojo.User" >
          <constructor-arg index="0" value="靠譜楊"></constructor-arg>
      </bean>
      
      public User(String name){
      		System.out.println("User的有參構造!");
      		this.name=name;
      	}
      
    2. 通過型別type="java.lang.String"

        <bean id="User" class="com.reliable.pojo.User" >
            <constructor-arg type="java.lang.String" value="靠譜楊"></constructor-arg>
        </bean>
    
    1. 通過引數名name="name" value="reliable"
        <bean id="User" class="com.reliable.pojo.User" >
            <constructor-arg name="name" value="reliable"></constructor-arg>
        </bean>
    

    總結:在配置檔案載入的時候,Spring容器中管理的物件就已經初始化成功了!

2、Spring的配置

2.1、別名

    <!--別名-->
    <alias name="User" alias="new_user"></alias>

2.2、Bean的配置

<?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
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--
    型別 變數名 = new 型別();
    Hello hello = new Hello();

    bean就是java物件 , 由Spring建立和管理
    bean = 一個物件
    其中
    id = 變數名
    class = new的物件型別
    property相當於給物件裡的屬性設定一個值
    -->
    <bean id="Hello" class="com.reliable.pojo.Hello">
        <property name="name" value="Spring"/>
    </bean>
    <!-- 無參 -->
    <!--<bean id="User" class="com.reliable.pojo.User">-->
        <!--<property name="name" value="靠譜"></property>-->
    <!--</bean>-->
    <!--有參第一種,index-->
    <!--<bean id="User" class="com.reliable.pojo.User" >
        <constructor-arg index="0" value="靠譜楊"></constructor-arg>
    </bean>-->
    <!-- 2 型別-->
   <!-- <bean id="User" class="com.reliable.pojo.User" >
        <constructor-arg type="java.lang.String" value="靠譜楊"></constructor-arg>
    </bean>-->
    <!-- 3 引數名字 -->
    <bean id="User" class="com.reliable.pojo.User" >
        <constructor-arg name="name" value="User"></constructor-arg>
    </bean>
    <bean id="User1" class="com.reliable.pojo.User1">
        <constructor-arg name="name" value="User1"></constructor-arg>
    </bean>
    <!--別名 如果新增的別名 都可以使用-->
    <alias name="User" alias="new_user"></alias>
</beans>

2.3、import

一般用於團隊開發使用,可以將多個配置檔案匯入合併為一個

    <!--import -->
    <import resource="beans1.xml"></import>

3、依賴注入(DI)

3.1 構造器注入

  • 依賴注入:Set注入
    • 依賴:bean物件的建立依賴於容器
    • 注入:bean物件中的所有屬性,由容器來注入!

3.2、Set方式注入【重點】

  • 複雜型別
public class Address {
	private String address;
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
}
  • 實體物件
import java.util.*;

public class Student {
	public String getName() {
		return name;
	}

	public Address getAddress() {
		return address;
	}

	public String[] getBooks() {
		return books;
	}

	public List<String> getHobbies() {
		return hobbies;
	}

	public Map<String, String> getCard() {
		return card;
	}

	public Set<String> getGames() {
		return games;
	}

	public String getWife() {
		return wife;
	}

	public Properties getInfo() {
		return info;
	}
	private String name;
	private Address address;
	private String[] books;
	private List<String> hobbies;
	private Map<String,String> card;
	private Set<String> games;
	private String wife;
	private Properties info;
	public void setName(String name) {
		this.name = name;
	}
	public void setAddress(Address address) {
		this.address = address;
	}
	public void setBooks(String[] books) {
		this.books = books;
	}
	public void setHobbies(List<String> hobbies) {
		this.hobbies = hobbies;
	}
	public void setCard(Map<String, String> card) {
		this.card = card;
	}
	public void setGames(Set<String> games) {
		this.games = games;
	}
	public void setWife(String wife) {
		this.wife = wife;
	}
	public void setInfo(Properties info) {
		this.info = info;
	}

	@Override
	public String toString() {
		return "Student{" +
				"name='" + name + '\'' +
				", address=" + address +
				", books=" + Arrays.toString(books) +
				", hobbies=" + hobbies +
				", card=" + card +
				", games=" + games +
				", wife='" + wife + '\'' +
				", info=" + info +
				'}';
	}
	//show方法
	public void show(){
		System.out.println("name="+ name
				+ ",address="+ address.getAddress()
				+ ",books="
		);
		for (String book:books){
			System.out.print("<<"+book+">>\t");
		}
		System.out.println("\n愛好:"+ hobbies);
		System.out.println("card:"+card);
		System.out.println("games:"+games);
		System.out.println("wife:"+wife);
		System.out.println("info:"+info);
	}
}


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
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="Address" class="com.kuang.pojo.Address">
        <property name="address" value="石家莊"></property>
    </bean>
    <bean id="Student" class="com.kuang.pojo.Student">
        <!-- 第一種:普通值注入 -->
        <property name="name" value="楊傳偉"></property>
        <!-- 第二種:ref注入 -->
        <property name="address" ref="Address"></property>
        <!-- 第三種:陣列注入 -->
        <property name="books">
            <array>
                <value>《紅樓夢》</value>
                <value>《西遊記》</value>
                <value>《水滸傳》</value>
                <value>《三國演義》</value>
            </array>
        </property>
        <!-- 第四種:List注入 -->
        <property name="hobbies">
            <list>
                <value>聽音樂</value>
                <value>看電影</value>
                <value>敲程式碼</value>
                <value>攝影</value>
            </list>
        </property>

        <!-- 第五種:Map注入 -->

        <property name="card">
            <map>
                <entry key="IDcard" value="1234567"></entry>
                <entry key="STcard" value="7654321"></entry>
            </map>
        </property>
        <!-- 第六種:Set注入 -->
        <property name="games">
            <set>
                <value>跑跑卡丁車官方競速版</value>
                <value>王者榮耀</value>
            </set>
        </property>

        <!-- 第七種:設定空值 -->
        <property name="wife">
            <null></null>
        </property>

        <!--properties-->
        <property name="info">
            <props>
                <prop key="學號">20194074</prop>
                <prop key="性別">男</prop>
                <prop key="姓名">楊傳偉</prop>
                <prop key="username">reliable</prop>
                <prop key="userpass">resetpass01</prop>
            </props>
        </property>
    </bean>
</beans>

3.3、拓展方式注入

使用p名稱空間和c名稱空間

使用:

package com.kuang.pojo;

public class User {
	private String name;
	private int age;

	public User(String name,int age) {
		this.name = name;
		this.age=age;
	}
	public User(){};
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "User{" +
				"name='" + name + '\'' +
				", age=" + age +
				'}';
	}
}

配置檔案:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--P(屬性: properties)名稱空間 , 屬性依然要設定set方法-->
    <bean id="user" class="com.kuang.pojo.User" p:name="靠譜" p:age="21"/>
    <!--C(構造: Constructor)名稱空間 , 屬性依然要設定set方法-->
    <bean id="user2" class="com.kuang.pojo.User" c:name="狂神" c:age="18"/>
</beans>

測試:

	public void test2(){
		ApplicationContext context=new ClassPathXmlApplicationContext("beans03.xml");
		User user = context.getBean("user", User.class);
		System.out.println(user);
		User user2 = context.getBean("user2", User.class);
		System.out.println(user2);
	}

注意

要引入c和p名稱空間:

xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"