天天看點

Spring_Ioc基本配置使用(基于xml)1、IOC簡介2、容器3、xml配置4、依賴5、(SPEL)Spring表達式語言

Spring_Ioc

  • 1、IOC簡介
    • 1.1、什麼是IOC
  • 2、容器
    • 2.1、容器概述
      • 2.1.1、配置中繼資料
      • 2.1.2、擷取bean的方式
  • 3、xml配置
  • 4、依賴
    • 4.1、依賴注入
    • 4.2、注入方式
      • 4.2.1、普通的注入方式
      • 4.2.2、使用P命名空間簡化基于setter屬性注入XML配置
      • 4.2.3、使用c命名空間簡化基于構造函數的XML配置
    • 4.3、屬性介紹
      • 4.3.1、depends-on 依賴
      • 4.3.2、lazy-init 懶加載
      • 4.3.3、scope 作用域
      • 4.3.4、執行個體化bean
      • 4.3.5、自動注入
    • 4.4、bean的生命周期
    • 4.5、外部bean和資源檔案引入
      • 4.5.1、配置第三方的bean
      • 4.5.2、引入外部屬性資源檔案
  • 5、(SPEL)Spring表達式語言

1、IOC簡介

1.1、什麼是IOC

IOC是Inversion of Control的縮寫,多數書籍翻譯成“控制反轉”。

是Spring架構裡面管理對象的一個容器。

2、容器

2.1、容器概述

ApplicationContext是Spring容器IOC實作的代表,它負責執行個體化、配置群組裝Bean。容器通過讀取配置中繼資料擷取有關執行個體化、配置群組裝哪些對象的說明。配置中繼資料可以使用xml、Java注解和Java代碼來呈現,它允許你處理應用程式的對象與其它對象之間的互相依賴關系。

2.1.1、配置中繼資料

1、使用xml的配置:

2、使用注解的配置:Spring2.5支援基于注解的中繼資料配置,SSM架構中使用。

3、基于Java的配置:從Spring3.0開始,由Spring JavaConfig項目提供的功能已經成為Spring核心架構的一部分。是以,你可以使用Java配置來代替xml配置定義外部bean。從Spring4.0開始支援Springboot1.0後,Springboot完全采用JavaConfig的形式進行開發。

2.1.2、擷取bean的方式

1、.class的方式:
ApplicationContext ioc = new ClassPathXmlApplicationContext("springIoc.xml");
User user = ioc.getBean(User.class);
           
2、通過類的名字或者id擷取:
//<bean class="cn.ale.beans.User" id="user"></bean>
ApplicationContext ioc = new ClassPathXmlApplicationContext("springIoc.xml");
User user = (User) ioc.getBean("user");
           
3、通過類的名字加類型(.class)擷取:
//<bean class="cn.ale.beans.User" id="user1"></bean>
//<bean class="cn.ale.beans.User" id="user2"></bean>
ApplicationContext ioc = new ClassPathXmlApplicationContext("springIoc.xml");
User user = ioc.getBean("user1",User.class);
           

3、xml配置

1、description

用來描述一個bean的作用

具體用法如下:

Spring_Ioc基本配置使用(基于xml)1、IOC簡介2、容器3、xml配置4、依賴5、(SPEL)Spring表達式語言

2、import

在一個xml檔案中導入另外一個檔案

具體用法如下:

Spring_Ioc基本配置使用(基于xml)1、IOC簡介2、容器3、xml配置4、依賴5、(SPEL)Spring表達式語言

3、alias

設定别名

具體用法如下:

Spring_Ioc基本配置使用(基于xml)1、IOC簡介2、容器3、xml配置4、依賴5、(SPEL)Spring表達式語言
設定别名也可以使用如下方式,在name屬性中,使用“空格”、“逗号”、“分号”分離,用法如下:
Spring_Ioc基本配置使用(基于xml)1、IOC簡介2、容器3、xml配置4、依賴5、(SPEL)Spring表達式語言

4、依賴

4.1、依賴注入

1、基于setter方法的注入
<!-- spring.xml -->
<!-- 基礎setter的依賴注入 -->
<!-- name屬性對應的set方法的名字 -->
<bean class="cn.ale.beans.User" id="setterUser">
    <property name="age" value="12"></property>
    <property name="userName" value="阿樂"></property>
    <property name="realName" value="小樂樂"></property>
</bean>
           
ApplicationContext ioc = new ClassPathXmlApplicationContext("springIoc.xml");
User user = ioc.getBean("setterUser",User.class);
           
2、基于構造函數的注入
<!-- 基礎構造函數的依賴注入 -->
<!-- 可以隻有value屬性 -->
<!-- 如果省略name屬性,一定要注意指派順序 -->
<!-- 也可以使用index屬性,下标從0開始 -->
<!-- type屬性可以指定參數類型 -->
<bean class="cn.ale.beans.User" id="structUser">
    <constructor-arg name="age" value="12"></constructor-arg>
    <constructor-arg name="userName" value="阿樂"></constructor-arg>
    <constructor-arg name="realName" value="小s樂樂"></constructor-arg>
</bean>
           
ApplicationContext ioc = new ClassPathXmlApplicationContext("springIoc.xml");
User user = ioc.getBean("structUser",User.class);
           

4.2、注入方式

4.2.1、普通的注入方式

//Person
private Integer id;
private String name;
private String gender;
private Date birthday;
private List<String> hobbies;
private Map<Integer,String> course;
private Wife wife;
private List<Children> children;

// Wife
private Integer age;
private String name;

// Children
private Integer id;
private String name;
           
<!--Spring.xml-->
<bean class="cn.ale.beans.Wife" id="wife">
    <property name="age" value="18"></property>
    <property name="name" value="哈哈哈"></property>
</bean>

<bean class="cn.ale.beans.Children" id="children">
    <property name="id" value="123"></property>
    <property name="name" value="啦啦啦"></property>
</bean>

<bean id="dateFormat" class="java.text.SimpleDateFormat">
    <constructor-arg value="yyyy-MM-dd" />
</bean>
<bean class="cn.ale.beans.Person" id="person">
    <property name="id" value="11"></property>
    <property name="name">
        <null></null>
    </property>
    <property name="gender" value=""></property>
    <!-- 引入外部bean -->
    <!--<property name="wife" ref="wife"></property>-->
    <!-- 引入内部bean -->
    <property name="wife">
        <bean class="cn.ale.beans.Wife" id="wife">
            <property name="age" value="18"></property>
            <property name="name" value="哈哈哈"></property>
        </bean>
    </property>
	<!-- 日期格式的注入 -->
    <property name="birthday">
        <bean factory-bean="dateFormat" factory-method="parse">
            <constructor-arg value="2015-12-31" />
        </bean>
    </property>
    <!-- List指派 -->
    <property name="hobbies">
        <list>
            <value>唱歌</value>
            <value>打乒乓球</value>
        </list>
    </property>
    <!-- map指派 -->
    <property name="course">
        <map>
            <entry key="111" value="111"></entry>
            <entry key="222" value="222"></entry>
        </map>
    </property>
    <!-- List的模型指派 -->
    <property name="children">
        <list>
            <ref bean="children"></ref>
            <bean class="cn.ale.beans.Children" name="children3"></bean>
        </list>
    </property>
</bean>
           

4.2.2、使用P命名空間簡化基于setter屬性注入XML配置

确認頭部導入xmlns:p=“http://www.springframework.org/schema/p”
Spring_Ioc基本配置使用(基于xml)1、IOC簡介2、容器3、xml配置4、依賴5、(SPEL)Spring表達式語言
<!-- 使用P命名空間簡化基于setter屬性注入XML配置 -->
<bean class="cn.ale.beans.Wife" id="wife2" p:age="10" p:name="蛤蛤蛤"></bean>
<bean class="cn.ale.beans.Person" id="person2" p:name="姓名" p:wife-ref="wife2">
    <property name="hobbies">
        <list>
            <value>唱歌</value>
            <value>打乒乓球</value>
        </list>
    </property>
</bean>
           
ApplicationContext ioc = new ClassPathXmlApplicationContext("springIoc.xml");
Person person = ioc.getBean("person2",Person.class);
           

4.2.3、使用c命名空間簡化基于構造函數的XML配置

确認頭部導入xmlns:c=“http://www.springframework.org/schema/c”
Spring_Ioc基本配置使用(基于xml)1、IOC簡介2、容器3、xml配置4、依賴5、(SPEL)Spring表達式語言
ApplicationContext ioc = new ClassPathXmlApplicationContext("springIoc.xml");
Children children = ioc.getBean("children2",Children.class);
           

4.3、屬性介紹

4.3.1、depends-on 依賴

<!-- 控制bean的加載順序,例如children在User之前加載 -->
<bean class="cn.ale.beans.User" id="user" depends-on="children"></bean>
<bean class="cn.ale.beans.Children" id="children"></bean>
           

4.3.2、lazy-init 懶加載

<!-- 懶加載,對象在使用的時候才會加載 -->
<bean class="cn.ale.beans.Children" id="children" lazy-init="true"></bean>
           

4.3.3、scope 作用域

singleton 單例

<!-- 單例,隻會建立一個Bean -->
<bean class="cn.ale.beans.Children" id="children" scope="singleton"></bean>
           

prototype 多例

<!-- 多例,用幾次建立幾個Bean -->
<bean class="cn.ale.beans.Children" id="children" scope="prototype"></bean>
           

request

session

application

websocket

4.3.4、執行個體化bean

1、使用靜态工廠方法執行個體化bean
<!-- 使用靜态工廠方法執行個體化bean -->
<bean class="cn.ale.beans.Children" id="children" factory-method="creatChildren"></bean>
           
// Person
public static Children creatChildren(){
    Children children = new Children();
    children.setName("孩子");
    return children;
}

// Children
Children extends Person
           
2、使用執行個體化工廠初始化bean
<!-- 先将執行個體工廠初始化進來 -->
<bean class="cn.ale.beans.PersonFactory" id="personFactory"></bean>
<!-- 使用執行個體化工廠将bean裝載進去 -->
<bean class="cn.ale.beans.Person" id="person" factory-bean="personFactory" factory-method="creatPersonFactoryMethod"></bean>
           
// PersonFactory
public class PersonFactory {
    public Person creatPersonFactoryMethod(){
        Children children = new Children();
        children.setName("孩子22");
        return children;
    }
}

// Test.class
ApplicationContext ioc = new ClassPathXmlApplicationContext("springHighIoc.xml");
Person person = ioc.getBean(Person.class);
           

4.3.5、自動注入

1、byType: 是要在IOC容器中找到,就會自動注入
<!-- byType  根據參數類型去自動比對,
當出現多個比對類型或者沒有找到一個可以比對的類型則會報錯-->
<bean class="cn.ale.beans.Person" id="person" autowire="byType"></bean>
<bean class="cn.ale.beans.Wife" id="wife">
    <property name="age" value="18"></property>
    <property name="name" value="阿樂"></property>
</bean>
           
2、byName: 根據set方法的名字去比對
<!-- 自動注入 -->
<!-- 
     byName  根據set方法的名字去比對
 -->
<bean class="cn.ale.beans.Person" id="person" autowire="byName"></bean>
<bean class="cn.ale.beans.Wife" id="wife">
    <property name="age" value="18"></property>
    <property name="name" value="阿樂"></property>
</bean>
<bean class="cn.ale.beans.Wife" id="wife2">
    <property name="age" value="18"></property>
    <property name="name" value="阿樂2"></property>
</bean>
           
//Person.java
private Wife wife;
public Wife getWife() {
    return wife;
}
public void setWife(Wife wife) {
    this.wife = wife;
}

//Test.java
ApplicationContext ioc = new ClassPathXmlApplicationContext("springHighIoc.xml");
Person person = ioc.getBean(Person.class);
System.out.println(person.toString());
           
控制台如下顯示:
Spring_Ioc基本配置使用(基于xml)1、IOC簡介2、容器3、xml配置4、依賴5、(SPEL)Spring表達式語言
3、constructor:首先會根據byName去自動比對,如果沒有找到,則會比對byType
<!-- constructor
   1、首先會去找Person裡面所有的構造函數
   2、找到之後會比對此構造函數所有的參數,如果在IOC中可以比對到構造函數中所有的參數,則自動注入
   特點:首先會根據byName去自動比對,如果沒有找到,則會比對byType
   		當類型出現多個會注入失敗,但是程式不會報錯
        這個時候會有兩個參數可以解決
        primary="true"   優先注入
        autowire-candidate="false" 不參與自動注入
-->
<bean class="cn.ale.beans.Person" id="person" autowire="constructor"></bean>
<bean class="cn.ale.beans.Wife" id="wife3" autowire-candidate="false">
    <property name="age" value="18"></property>
    <property name="name" value="阿樂"></property>
</bean>
<bean class="cn.ale.beans.Wife" id="wife2" primary="true">
    <property name="age" value="18"></property>
    <property name="name" value="阿樂22"></property>
</bean>
<bean class="cn.ale.beans.User" id="user"></bean>
           
// Person.java
public Person() {
}
public Person(Wife wife,User user) {
    this.wife = wife;
}
           

4.4、bean的生命周期

1、使用接口的方法實作:

實作InitializingBean接口并實作afterPropertiesSet方法,初始化bean

實作DisposableBean接口并實作destroy方法,銷毀bean

//Spring.xml
<bean class="cn.ale.beans.Wife" id="wife"></bean>

//Test.java
ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("springHighIoc.xml");
Wife wife = ioc.getBean(Wife.class);
ioc.close();

// Wife.java
public class Wife implements InitializingBean, DisposableBean {
    public void afterPropertiesSet() throws Exception {
        System.out.println("初始化Wife加載。");
    }
    public void destroy() throws Exception {
        System.out.println("銷毀Wife。");
    }
}
           
控制台顯示如下:
Spring_Ioc基本配置使用(基于xml)1、IOC簡介2、容器3、xml配置4、依賴5、(SPEL)Spring表達式語言

2、基于配置的方法實作:

init-method=“initBeanByConfig”

destroy-method=“destroyBeanByConfig”

設定以上兩個屬性對應的對象中的兩個方法

//Spring.xml
<bean class="cn.ale.beans.Wife" id="wife" init-method="initBeanByConfig" destroy-method="destroyBeanByConfig"></bean>

//Test.java
ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("springHighIoc.xml");
Wife wife = ioc.getBean(Wife.class);
ioc.close();

// Wife.java
public class Wife implements InitializingBean, DisposableBean {
    public void afterPropertiesSet() throws Exception {
        System.out.println("初始化Wife加載基于接口。");
    }
    public void destroy() throws Exception {
        System.out.println("銷毀Wife基于接口。");
    }
    public void initBeanByConfig() throws Exception {
        System.out.println("初始化Wife加載基于配置。");
    }
    public void destroyBeanByConfig() throws Exception {
        System.out.println("銷毀Wife基于配置。");
    }
}
           

控制台顯示如下:

Spring_Ioc基本配置使用(基于xml)1、IOC簡介2、容器3、xml配置4、依賴5、(SPEL)Spring表達式語言

4.5、外部bean和資源檔案引入

4.5.1、配置第三方的bean

這裡我們以引入mysql資料庫為例:

1、配置pom.xml檔案,加入以下兩個包

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.21</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
</dependency>
           
2、spring注入bean
<!-- 配置第三方的bean -->
<bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
    <property name="username" value="root"></property>
    <property name="password" value="123456"></property>
    <property name="url" value="jdbc:mysql://localhost:3306/test"></property>
    <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
</bean>
           
3、測試代碼
ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("springHighIoc.xml");
DruidDataSource dataSource = ioc.getBean("dataSource",DruidDataSource.class);
System.out.println(dataSource);
           
控制台如下顯示:
Spring_Ioc基本配置使用(基于xml)1、IOC簡介2、容器3、xml配置4、依賴5、(SPEL)Spring表達式語言

4.5.2、引入外部屬性資源檔案

<!-- 引入外部屬性資源檔案 -->
<context:property-placeholder location="db.properties"></context:property-placeholder>
           
<!-- db.properties -->
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/sam
username=root
password=root
           

5、(SPEL)Spring表達式語言

Spring Expression Language
<bean class="cn.ale.beans.Person" id="person">
    <!-- 運算符表達式 -->
    <property name="id" value="#{1+9}"></property>
    <!-- 引入外部bean -->
    <property name="wife" value="#{wife}"></property>
    <!-- 引入bean的屬性 -->
    <property name="name" value="#{wife.name}"></property>
    <!-- 引入bean的方法 -->
    <property name="gender" value="#{wife.getName()}"></property>
    <!-- 引入靜态方法 -->
    <property name="birthday" value="#{T(cn.ale.beans.Person).getNowDate()}"></property>
</bean>