Spring學習記錄1

Furrain發表於2020-12-13

Spring學習記錄1

1.基本例子

第一步匯入匯入spring的jar包,或者使用Maven引入spring依賴

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.2.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.2.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>5.2.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>

第二步有一個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"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- 配置user類-->
    <bean id="user" class="Furrain.User"></bean>
    <!--setter注入屬性-->
<!--    <bean id="book" class="Furrain.Book">-->
<!--        &lt;!&ndash;使用property完成屬性注入&ndash;&gt;-->
<!--        <property name="bName" value="驚悚樂園"></property>-->
<!--        <property name="bPrice" value="128"></property>-->
<!--    </bean>-->

    <!--用有參構造注入屬性-->
    <bean id="orders" class="Furrain.Orders">
        <constructor-arg name="oAddress" value="peiking"></constructor-arg>
        <constructor-arg name="oName" value="kimJisoo"></constructor-arg>
    </bean>

    <!--p空間注入-->
    <bean id="book" class="Furrain.Book" p:bName ="異常生物見聞錄" p:bPrice="199">
    <!-- 注入null-->
<!--        <property name="bAuthor">-->
<!--            <null></null>-->
<!--        </property>-->
        <!--特殊符號,如<>
        1.html的轉義符&lt;&gt;
        2.特殊符號寫進CDATA
        -->
        <property name="bAuthor">
            <value><![CDATA[<<1122>>]]></value>
        </property>
    </bean>
</beans>

第三步,使用spring生成類例項

    @Test
    public void add() {
        // 載入配飾檔案
        ApplicationContext context = new ClassPathXmlApplicationContext("spring/bean1.xml");
        User user = context.getBean("user",User.class);
        System.out.println(user);
        user.add();
    }

2.依賴注入

1.生成用例
2.依賴注入 DI DI是IOC裡的一個步驟吧,感覺。

setter依賴注入

見上面例子

有參構造

見上面例子

注入null.

見上面例子

注入特殊值

見上面例子

注入自定義類物件

前面都是value
外部bean自定義物件需要ref引用其他的bean例項
內部就無所謂了

package Furrain.Dao;

/**
 * <Description>
 *
 * @author Furrain
 * @version 1.0
 * @ClassName UserDao
 * @createDate 2020/12/13 0:12
 * @see Furrain.Dao
 */
public interface UserDao {
    public void update();
}

package Furrain.Dao;

/**
 * <Description>
 *
 * @author Furrain
 * @version 1.0
 * @ClassName UserDaoImpl
 * @createDate 2020/12/13 0:12
 * @see Furrain.Dao
 */
public class UserDaoImpl implements UserDao{
    @Override
    public void update() {
        System.out.println("UserDao update....");
    }
}
package Furrain.Service;

import Furrain.Dao.UserDao;
import Furrain.Dao.UserDaoImpl;

/**
 * <Description>
 *
 * @author Furrain
 * @version 1.0
 * @ClassName UserService
 * @createDate 2020/12/13 0:13
 * @see Furrain.Service
 */
public class UserService {
    private UserDao Udao;

    public void setUdao(UserDao udao) {
        Udao = udao;
    }

    public void add() {
        System.out.println("service add...");
        Udao.update();
    }
}

<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--外部bean-->
        <bean id="userService" class="Furrain.Service.UserService">
    <!--注入userDao類物件.
    name:需要注入物件的名字
    ref:外部的bean
    -->
            <property name="Udao" ref="userDao"></property>
        </bean>
        <bean id="userDao" class="Furrain.Dao.UserDaoImpl"></bean>

    <!--內部bean-->
    <bean id="userService" class="Furrain.Service.UserService">
        <property name="Udao">
            <bean class="Furrain.Dao.UserDaoImpl"></bean>
        </property>
    </bean>
</beans>

測試

    @Test
    public void add() {
        ApplicationContext context= new ClassPathXmlApplicationContext("spring/bean2.xml");
        UserService uiService = context.getBean("userService",UserService.class);
        uiService.add();
    }

級聯賦值

根據講述者說明,其實上面的內部bean和外部bean也算級聯賦值(意思呼叫一個類的時候,呼叫了另一個類,另一個類生成了例項,也進行了初始化賦值)
還有一種在一個bean的內部給另一個bean的值賦值,但是需要一個getter方法

package Furrain.bean;

/**
 * <Description>
 *
 * @author Furrain
 * @version 1.0
 * @ClassName Emp
 * @createDate 2020/12/13 1:03
 * @see Furrain.bean
 */
public class Emp {
    private String eName;
    public void seteName(String eName) {
        this.eName = eName;
    }

    public Dept geteDept() {
        return eDept;
    }

    public void seteDept(Dept eDept) {
        this.eDept = eDept;
    }

    private Dept eDept;

    public void printDemo() {
        System.out.println(eName);
        System.out.println(eDept);
    }
}

package Furrain.bean;

/**
 * <Description>
 *
 * @author Furrain
 * @version 1.0
 * @ClassName Dept
 * @createDate 2020/12/13 1:03
 * @see Furrain.bean
 */
public class Dept {
    private String dName;

    public void setdName(String dName) {
        this.dName = dName;
    }

    @Override
    public String toString() {
        return dName;
    }
}

<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="dept" class="Furrain.bean.Dept"></bean>
    <bean id="emp" class="Furrain.bean.Emp">
        <property name="eName" value="王二狗子"></property>
        <property name="eDept" ref="dept"></property>
        <property name="eDept.dName" value="晶片業務部"></property>
    </bean>
</beans>

注入集合屬性

陣列/list/map/set

package Furrain;

import javafx.scene.control.ListCell;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <Description>
 *
 * @author Furrain
 * @version 1.0
 * @ClassName Stu
 * @createDate 2020/12/13 1:25
 * @see Furrain
 */
public class Stu {
    private String[] courses;

    private List<String> likeGirlsList;

    private Map<String,String> infoMap;

    private Set<String> beLikedGirlsSet;

    private List<Pet> pets;

    public void setPets(List<Pet> pets) {
        this.pets = pets;
    }

    public void setCourses(String[] courses) {
        this.courses = courses;
    }

    public void setLikeGirlsList(List<String> likeGirlsList) {
        this.likeGirlsList = likeGirlsList;
    }

    public void setInfoMap(Map<String, String> infoMap) {
        this.infoMap = infoMap;
    }

    public void setBeLikedGirlsSet(Set<String> beLikedGirlsSet) {
        this.beLikedGirlsSet = beLikedGirlsSet;
    }

    public void printDemo() {
        System.out.println(Arrays.toString(courses));
        System.out.println(infoMap);
        System.out.println(beLikedGirlsSet);
        System.out.println(likeGirlsList);
        System.out.println(pets);
    }
}


package Furrain;

/**
 * <Description>
 *
 * @author Furrain
 * @version 1.0
 * @ClassName Pet
 * @createDate 2020/12/13 1:41
 * @see Furrain.Service
 */
public class Pet {
    private String pName;

    public void setpName(String pName) {
        this.pName = pName;
    }

    @Override
    public String toString() {
        return pName;
    }
}

<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="stu" class="Furrain.Stu">
        <property name="courses">
            <array>
                <value>java</value>
                <value>c++</value>
                <value>pathon</value>
            </array>
        </property>
        <property name="likeGirlsList">
            <list>
                <value>張蘭</value>
                <value>李花</value>
            </list>
        </property>
        <property name="infoMap">
            <map>
                <entry key="身高" value="177"></entry>
                <entry key="體重" value="77"></entry>
            </map>
        </property>
        <property name="beLikedGirlsSet">
            <set>
                <value>王虎</value>
                <value>趙曉華</value>
            </set>
        </property>
        <property name="pets">
            <list>
                <ref bean="pet1"></ref>
                <ref bean="pet2"></ref>
                <ref bean="pet3"></ref>
                <ref bean="pet4"></ref>
            </list>
        </property>
    </bean>
    <bean id="pet1" class="Furrain.Pet" p:pName="花花"></bean>
    <bean id="pet2" class="Furrain.Pet" p:pName="草草"></bean>
    <bean id="pet3" class="Furrain.Pet" p:pName="小黑"></bean>
    <bean id="pet4" class="Furrain.Pet" p:pName="大黃"></bean>
</beans>

提取公共資料

1.xml增加util名稱空間,並抽取出公共部分

具體修改

<?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:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">
        <!--**********************這裡******************************-->
    <bean id="stu" class="Furrain.Stu">
        <property name="courses">
            <array>
                <value>java</value>
                <value>c++</value>
                <value>pathon</value>
            </array>
        </property>
        <property name="likeGirlsList">
            <list>
                <value>張蘭</value>
                <value>李花</value>
            </list>
        </property>
        <property name="infoMap">
            <map>
                <entry key="身高" value="177"></entry>
                <entry key="體重" value="77"></entry>
            </map>
        </property>
        <property name="beLikedGirlsSet">
            <set>
                <value>王虎</value>
                <value>趙曉華</value>
            </set>
        </property>
        <property name="pets" ref="petList">
        </property>
    </bean>
    <bean id="pet1" class="Furrain.Pet" p:pName="花花"></bean>
    <bean id="pet2" class="Furrain.Pet" p:pName="草草"></bean>
    <bean id="pet3" class="Furrain.Pet" p:pName="小黑"></bean>
    <bean id="pet4" class="Furrain.Pet" p:pName="大黃"></bean>
    <!--**********************這裡******************************-->
    <util:list id="petList">
        <ref bean="pet1"></ref>
        <ref bean="pet2"></ref>
        <ref bean="pet3"></ref>
        <ref bean="pet4"></ref>
    </util:list>
    <!--**********************這裡******************************-->
    <bean id="teacher" class="Furrain.Teacher">
        <property name="pets" ref="petList"></property>
    </bean>
</beans>
package Furrain;

import Furrain.Pet;

import java.util.List;

/**
 * <Description>
 *
 * @author Furrain
 * @version 1.0
 * @ClassName Teacher
 * @createDate 2020/12/13 1:54
 * @see Furrain.Service
 */
public class Teacher {
    public void setPets(List<Pet> pets) {
        this.pets = pets;
    }

    private List<Pet> pets;

    public void printDemo() {
        System.out.println(pets);
    }
}

這樣,老師和學生就可以使用一樣的pets了…

Bean的分類

普通Bean

之前用到的都是普通Bean,即class定義的是什麼型別的,返回的就是什麼型別

FactoryBean

返回的是一個不確定型別的物件

例子

package Furrain.FactorBean;

import Furrain.Pet;
import org.springframework.beans.factory.FactoryBean;

/**
 * <Description>
 *
 * @author Furrain
 * @version 1.0
 * @ClassName MyBean
 * @createDate 2020/12/13 2:30
 * @see Furrain.FactorBean
 */
public class MyBean implements FactoryBean<Pet> {
    @Override
    public Pet getObject() throws Exception {
        Pet pet = new Pet();
        pet.setpName("王老狗");
        return pet;
    }

    @Override
    public Class<?> getObjectType() {
        return Pet.class;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }
}

package Furrain;

/**
 * <Description>
 *
 * @author Furrain
 * @version 1.0
 * @ClassName Pet
 * @createDate 2020/12/13 1:41
 * @see Furrain.Service
 */
public class Pet {
    private String pName;

    public void setpName(String pName) {
        this.pName = pName;
    }

    @Override
    public String toString() {
        return pName;
    }
}

<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- 配置user類-->
    <bean id="mybean" class="Furrain.FactorBean.MyBean"></bean>
</beans>

測試

    @Test
    public void testFactoryBean() {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring/bean5.xml");
        Pet mybean = context.getBean("mybean", Pet.class);
        System.out.println(mybean);
    }

雖然xml是Mybean,但是實際返回的是pet,實現了FactoryBean介面。

bean的作用域(重要)

1.spring中可以設定生成的是單例項還是多例項
2.預設情況下,spring生成的是單例項

預設下,不管用sprinmg建立多遍,得到的例項地址是一致的,可以自己試一下

如何設定多例項

spring的bean標籤中有屬性(scope)可以設定

scope的值:
1.預設的:singleton
2.prototype 多例項

區別

singleton與prototype
1.一個單的一個多的例項
2.第一個是單例項,很好理解,在載入配置檔案的時候, ApplicationContext context = new ClassPathXmlApplicationContext(“spring/xxxx.xml”);
就可以生成例項物件了,因為不管怎麼調,返回的都是這一個。
既然第二個是多的,就有一個問題,因為他不知道我要用幾個,那他就不會提前就new出我想要的例項,那就是在呼叫時new XXXX xxx=
context.getBean(“xxx”,XXXX.class);

bean的生命週期(重要)

未完待續…

相關文章