JAVA框架篇(一)spring介紹,基礎搭建,Bean的配置,屬性注入,生命週期


Spring是一個輕量級的開源框架,它操作簡單維護容易。
Spring的核心是IOC反轉控制器和AOP
Spring是一個容器,它本身沒有什麼功能。當你放了什麼樣的對象進去它就會有什麼功能。
Spring有7大模塊,其中core是基礎.。開發時根據需要選擇必要的組件而忽略其他組件,達到最小依賴.也就是這幾大模塊中都有對應的jar包。用到那個組件就導對應的包進去就好。

在這裏插入圖片描述

Spring的基礎使用就是要會進行Spring的基礎搭建和Bean的配置和屬性注入。

Spring基礎搭建和JAVA對象配置

IOC反轉控制器
IOC就是將我們平時new對象和給對象的屬性set值的動作交給IOC來完成.我們搭建的Spring將會有什麼功能就靠這個IOC了

1,配置Spring

(1)首先要導入Spring的jar包。即包括beans,core,context,expression和log包.
Spring包下載地址:https://repo.spring.io/libs-release-local/org/springframework/spring/
在這裏插入圖片描述
(2)接着創建一個applicationContext.xml放在src目錄下,這個是Spring的配置文件的名稱。這個名稱不是固定的。但這是個約定。爲了人們方便維護所有項目的Spring配置文件所以都叫這個.
然後往這個XML添加一下頭信息。

<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>

(3)創建一個類,把這個類配置到applicationContext.xml

public class SpringEntity {
    public void springTest(){
        System.out.println("spring配置完成");
    }
}

XML

<!--id是自定義的對象名。class爲類所在的全包名-->
<bean id="SpringEntity" class="spring.SpringEntity"></bean>

Test類

    @Test
    public void springFun(){
        //創建一個ClassPathXmlApplicationContext對象並將applicationContext.xml的路徑寫進去
        ApplicationContext applicationContext =  new ClassPathXmlApplicationContext("applicationContext.xml");
        //接着在使用getBean(String beanName);方法來獲取對象
        SpringEntity springEntity = (SpringEntity)applicationContext.getBean("SpringEntity");
        springEntity.springTest();
        //這樣就完成了Spring的入門使用。讓Spring來幫我們創建一個對象
    }

效果如下:
在這裏插入圖片描述
–>Spring中配置bean的基本方式.使用<bean>標籤來表示配置一個JAVA類。裏面兩個基礎屬性.id表示這個類創建的對象的名稱。class爲這個類所在的全包名

<bean id="SpringEntity" class="spring.SpringEntity"></bean>

–>配置好後的操作步驟
(1)創建一個Spring容器

   //創建一個ClassPathXmlApplicationContext對象並傳入applicationContext的路徑
     ApplicationContext applicationContext =  new ClassPathXmlApplicationContext("applicationContext.xml");

(2)然後在調用getBean(String beanName)時beanName對應這個id.

上面只是基礎的配置一個JAVABean。Spring默認使用這個bean的無參構造來實例化該對象。Spring還可以通過工廠函數的方式來實例化對象。在實例化對象的同時也可以往裏面的屬性注入值。也能夠使用有參構造來實例化。

使用工廠函數實例化

–>靜態工廠函數實例化對象:
創建一個類添加一個靜態方法

public class FactoryMethod {
    /**
     * 靜態函數,返回一個對象
     */
    public static SpringEntity getSpringEntity(){
        return new SpringEntity();
    }
}

xml:
class:填工廠函數所在的全包名
id:填對應的靜態函數返回的類的對象的名稱
factory-method:靜態函數的函數名

<bean class="spring.FactoryMethod" id="springEntity" factory-method="getSpringEntity"></bean>

test:

    @Test
    public void springFun(){
        ApplicationContext applicationContext =  new ClassPathXmlApplicationContext("applicationContext.xml");
        //靜態工廠函數實例化一個對象.在xml配置好後直接根據id來獲取對象
        SpringEntity springEntity = (SpringEntity)applicationContext.getBean("springEntity");
        springEntity.springTest();
    }

–>動態工廠函數實例化對象:
創建一個類添加一個普通方法

public class FactoryMethod {
    /**
     * 動態函數,返回一個對象
     */
    public SpringEntity getSpringEntity(){
        return new SpringEntity();
    }
}

xml:
由於不是靜態的所以要先配置FactoryMethod的實例化bean,在配置目標對象的bean.然後在目標對象中添加兩個屬性
factory-bean:工廠函數的bean
factory-method:對應的動態工廠函數

<bean class="spring.FactoryMethod" id="factoryMethod" ></bean>
 <bean id="springEntity" factory-bean="factoryMethod" factory-method="getSpringEntity"></bean>

使用有參構造實例化

有這麼一個構造方法

public class SpringEntity {
    private String name;
    private String sex;
    public SpringEntity(String name, String sex) {
        this.name = name;
        this.sex = sex;
        System.out.println(this.name+"="+this.sex);
    }
}

xml:在xml配置的bean默認調用的無參構造來實例化。如果要使用有參構造實例化。則需要在bean的標籤體內添加constructor-arg標籤,其屬性如下:
index:參數的位置從0開始,比如上述的構造方法中index=0就表示String name.根據這個屬性可以選擇自己需要調用的那個構造方法。
type:參數的類型
value:要注入的值

    <bean id="springEntity" class="spring.SpringEntity">
        <constructor-arg index="0" type="java.lang.String" name="name" value="zhangsan" />
        <constructor-arg index="1" type="java.lang.String" name="sex" value="man"/>
    </bean>

test:

    @Test
    public void springFun(){
        ApplicationContext applicationContext =  new ClassPathXmlApplicationContext("applicationContext.xml");
        SpringEntity springEntity = (SpringEntity)applicationContext.getBean("springEntity");
    }

效果如下:
在這裏插入圖片描述

2,屬性注入

在普通的情況下,要對一個對象的屬性注入值都用setter方法或者構造方法。
上述的使用有參構造實例化就是使用有參構造來完成屬性注入.所以接下來說setter方式注入
在配置注入之前要確保這個類的屬性有對應的setter和getter方法
(1)基礎類型注入
在bean標籤體內添加property表示屬性。
name:屬性名
value:值

    <bean id="springEntity" class="spring.SpringEntity">
        <property name="name" value="zhangsan"/>
        <property name="sex" value="man"/>
     </bean>

這樣在實例化的同時給屬性賦值.效果如下
在這裏插入圖片描述

(2)ref引用注入
有時候你的實體會有一個引用類型即你的屬性是一個類

public class SpringEntity {
    /**
     * 引用類型,定義一個類的屬性
     */
    private Human human;
    //setter和getter
}
public class Human {
   private String name;
   
   //setter和getter
}

在xml中配置一個這樣類型是一個類的屬性。則要先配置這個屬性對應的類的bean,然後在property中添加ref屬性引用這個bean

   <!--先配置引用類型對應的類的bean-->
    <bean id="human" class="entry.Human">
        <property name="name" value="lisi" />
    </bean>
    <bean id="springEntity" class="spring.SpringEntity">
        <!--ref注入引用類型的屬性-->
        <property name="human" ref="human" />
     </bean>

效果如下:
在這裏插入圖片描述
(3)複雜類型注入
一個類中有時會定義一些複雜類型。比如數組,集合,map

public class SpringEntity {

    private Object[] array;
    private List<Object> list;
    private Map<Object,Object> map;
    //setter和getter
    }

xml:在property標籤體中添加內容。<array>標籤表示數組,<list>爲集合<map>爲map

    <bean id="springEntity" class="spring.SpringEntity">
        <property name="array">
            <!--數組用array標籤-->
            <array>
                <!--按順序賦值,基礎類型用value,引用類型用ref-->
                <!--value添加type可指定類型-->
                <value>1</value>
                <value type="java.lang.String">2</value>
                <ref bean="humen"/>
            </array>
        </property>
        <property name="list">
            <!--集合用list標籤-->
            <list>
                <!--同樣按順序賦值,基礎類型用value,引用類型用ref-->
                <!--value添加type可指定類型-->
                <value>1</value>
                <value type="java.lang.String">2</value>
                <ref bean="humen"/>
            </list>
        </property>
        <property name="map">
            <!--map用map標籤,key-type可以指定key的類型.默認基礎類型是String.-->
            <map>
                <!--按順序賦值,用key賦值key,value賦值value-->
                <!--value-type添加type可指定類型-->
              <entry key="1" value="1"  value-type="java.lang.String"/>
                <!--key-ref和value-ref注入引用類型-->
              <entry key-ref="humen" value-ref="humen" />
            </map>
        </property>
     </bean>

(4)prop類型注入
類中有Properties類型的屬性時,使用props來注入

public class SpringEntity {
   private Properties properties;
   //setter和getter
   }

xml:使用props標籤來給Properties類型的屬性注入值

    <bean id="springEntity" class="spring.SpringEntity">
       <property name="properties">
           <!--類中有Properties時用props標籤-->
           <!--value-type指定value類型-->
           <props>
               <!--元素使用prop,key屬性賦值key,標籤體賦值value-->
               <prop  key="driver">com.mysql.jdbc.Driver</prop>
               <prop key="user">root</prop>
           </props>
       </property>
     </bean>

效果如下:
在這裏插入圖片描述

3,Scope屬性,bean的作用域,單例和多例模式

bean標籤裏面有個Scope屬性,它用來指定配置的這個bean是多例還是單例。如果是單例那麼無論getBean()多少次獲得的都是同一個實例。如果是多例那麼每次getBean()都會獲得一個新實例。
設置Scope=“singleton” 表示單例
設置Scope=“prototype” 表示多例
Scope默認是單例

(1)singleton作用域
單例模式,bean不指定scope時默認爲singleton.單例,即這個bean在這個容器中只會創建一個實例,無論多少次getbean獲取的都是同一個實例

User user1 = (User) context.getBean("user");
User user2 = (User) context.getBean("user");
System.out.println(user1==user2);

結果返回true

(2),prototype作用域
多例模式,當指定bean的scope屬性爲prototype時,則這個bean在這個容器可以創建多個實例,即每次getbean獲取的實例都是不相同的

<bean class="com.etc.spring.entity.User" id="user" scope="prototype">
User user1 = (User) context.getBean("user");
User user2 = (User) context.getBean("user");
System.out.println(user1==user2);

結果返回false

4,Bean的生命週期

spring中Bean的生命週期默認是容器創建的時候創建,容器關閉的時候銷燬。
即執行:
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(“applicationContext.xml”);
這句話時,對象就創建了。
在執行
((AbstractApplicationContext)applicationContext).close();時對象銷燬

Bean裏面有兩個屬性init-method和destroy-method表示在對象創建時執行的方法和對象銷燬前執行的方法。用這兩個屬性來觀察Bean的生命週期
(1)首先在Bean對應的類上添加init和destroy方法

public class SpringEntity {
  public void init(){
      System.out.println("對象創建了");
  }
  public void destroy(){
      System.out.println("對象銷燬了");
  }
}

xml:然後在bean配上init-method和destroy-method

    <bean id="springEntity" class="spring.SpringEntity" init-method="init" destroy-method="destroy"></bean>

test:

//開啓容器,創建對象
ApplicationContext applicationContext =  new ClassPathXmlApplicationContext("applicationContext.xml");
//關閉容器,銷燬對象
((AbstractApplicationContext)applicationContext).close();

效果如下:
在這裏插入圖片描述
至於關閉的方法。由於ClassPathXmlApplicationContext沒有close方法但是AbstractApplicationContext有。所以需要強轉

5,Bean的懶加載.

上面說到,Bean在容器創建時就會創建。Bean標籤有一個屬性Lazy-Init它可以實現這個Bean在我們調用getBean()獲取的時候才創建。
Lazy-Init:默認值是default表示當容器創建時就實例化此對象,當設置成true時表示當調用getBean()方法時才實例化此對象。設置成false時和default效果一樣。

(1)未設置Lazy-Init時

 <bean id="springEntity" class="spring.SpringEntity" init-method="init" destroy-method="destroy"></bean>

效果如下:
在這裏插入圖片描述
(2)設置Lazy-Init且值爲true時

    <bean id="springEntity" class="spring.SpringEntity" lazy-init="true" init-method="init" destroy-method="destroy"></bean>

效果如下,中間設置了個3秒延遲。:
在這裏插入圖片描述

引入其他配置文件

1,引入xml
一個項目一般會有多個模塊.每個模塊都可能會有一個application.xml,而部署服務的時候爲了將這麼多的xml的內容都整合到一個裏面。就需要用到import標籤。它能夠把其他xml的內容導入進來.

<import resourse=”路徑” />

xml1:

<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">
    <import resource="applicationContext1.xml"/>
    <bean id="springEntity" class="spring.SpringEntity" lazy-init="true">
        <property name="human" ref="human"></property>
    </bean>
</beans>

xml2:

    <bean id="human" class="entry.Human" ></bean>

xml1的bean引用xml2的bean
效果如下:
在這裏插入圖片描述
2,引入properties
如果要在applicationContext.xml中引入properties的配置則需要用到context.
首先準備好一個properties和一個實體;
properties:

jdbc.driver=com.mysql.jdbc.Driver

實體:


public class SpringEntity {
   private String driver;
   //setter和getter
   }

步驟:
1,首先要配置context的xml頭信息
在這裏插入圖片描述

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
 http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
 http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context-4.2.xsd
">

2,接着使用以下標籤
格式固定,注意db.properties的路徑。如果放在src下就這樣寫.引入後使用${key}給實體的屬性注入值
xml:

<!--引入properties-->
<context:property-placeholder location="classpath:db.properties"/>

    <bean id="springEntity" class="spring.SpringEntity" lazy-init="true">
    <!--接着使用${key}來給注入值-->
        <property name="driver" value="${jdbc.driver}"></property>
    </bean>

效果如下:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章