[JAVAEE] 實驗03:Spring Bean的配置、實例化、作用域、生命周期與裝配方式

【一】實驗?zāi)康模?/h1>

(1)掌握Bean的實例化
(2)掌握Bean的裝配方式
(3)掌握Bean的作用域和生命周期

【二】結(jié)構(gòu):

1配置(不具體介紹)
2實例化:構(gòu)造方法實例化(最常用)、靜態(tài)工廠實例化、實例工廠實例化
3作用域
4生命周期
5裝配方式

【三】實驗代碼:

一、實例化

 BeanClass.java
package instance;
//一、bean的構(gòu)造方法之 實例化(最常用)
public class BeanClass {    
    public String message;
    public BeanClass() {
        message = "構(gòu)造方法實例化Bean";
    }
    public BeanClass(String s) {
        message = s;
    }
}
BeanInstanceFactory.java
package instance;
public class BeanInstanceFactory {
    public BeanClass createBeanClassInstance() {
        return new BeanClass("調(diào)用實例工廠方法實例化Bean");
    }
}

BeanStaticFactory.java

package instance;
//二、bean實例化之 靜態(tài)工廠實例化
public class BeanStaticFactory {
    
    private static BeanClass beanInstance = new BeanClass("調(diào)用靜態(tài)工廠方法實例化Bean");
    public static BeanClass createInstance() {
        return beanInstance;
    }
}

配置文件:ApplicationContext.xml

    <!-- 一、構(gòu)造方法實例化Bean -->
    <bean id="constructorInstance" class="instance.BeanClass" scope="prototype"/>
    
    <!-- 二、靜態(tài)工廠方法實例化Bean,createInstance為 靜態(tài)工廠類BeanStaticFactory中的靜態(tài)方法-->
    <bean id="staticFactoryInstance" class="instance.BeanStaticFactory"  factory-method="createInstance"/>
    
    <!-- 三、配置工廠 -->
    <bean id="myFactory" class="instance.BeanInstanceFactory"/>
    <!-- 還需要使用factory-bean屬性指定配置工廠,應(yīng)為這個是對象方法而不是類方法 ,使用factory-method屬性指定使用工廠中哪個方法實例化Bean-->
    <bean id="instanceFactoryInstance" factory-bean="myFactory" factory-method="createBeanClassInstance"/>

測試:TestInstance.java

package test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import instance.BeanClass;
public class TestInstance {
    public static void main(String[] args) {
        //初始化spring容器,通過路徑加載配置文件
        @SuppressWarnings("resource")
        ApplicationContext appCon = new ClassPathXmlApplicationContext("applicationContext.xml");
        //一、構(gòu)造方法的
        BeanClass b1 = (BeanClass)appCon.getBean("constructorInstance");
        System.out.println(b1 + "------" + b1.message);
        
        //二、靜態(tài)工廠的
        BeanClass b2 = (BeanClass)appCon.getBean("staticFactoryInstance");
        System.out.println(b2+ "------" +b2.message);
        
        //三、實例工廠的
        BeanClass b3 = (BeanClass)appCon.getBean("instanceFactoryInstance");
        System.out.println(b3+ "------" +b3.message);
        
    }
}
實例化1
實例化2
實例化3

二、作用域(可作用的范圍)

    <!-- 構(gòu)造方法實例化Bean ,并設(shè)置為 prototype,默認為singleleton-->
    <bean id="constructorInstance" class="instance.BeanClass" scope="prototype"/>
作用域1

三、生命周期

配置文件:

    <!-- 3.1、配置bean的生命周期,使用init-method屬性指定初始化方法,使用 destroy-method屬性指定銷毀方法-->
    <bean id="beanLife" class="life.BeanLife" init-method="initMyself" destroy-method="destroyMyself"/>


BeanLife.java
package life;
public class BeanLife {
    //相當于回調(diào),以后可以寫數(shù)據(jù)庫的方法
    public void initMyself() {
        System.out.println(this.getClass().getName() + "?執(zhí)行自定義的初始化方法");
    }
    public void destroyMyself() {
        System.out.println(this.getClass().getName() +"執(zhí)行自定義的銷毀方法");
    }
}
TestLife.java
package test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import life.BeanLife;
public class TestLife {
    public static void main(String[] args) {
        //初始化容器,加載配置文件
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        System.out.println("獲得對象前");
        BeanLife blife = (BeanLife)ctx.getBean("beanLife");
        
        System.out.println("獲得對象后" + blife);
        
        ctx.close();//關(guān)閉容器
    }
}
生命周期1
生命周期2

四、裝配方式(bean注入到容器的方式)

1.基于xml的裝配方式

    <!-- 4.1.1 使用構(gòu)造方法注入方式裝配ComplexUser實例 user1-->
    <bean id="user1" class="assemble.ComplexUser">
        <constructor-arg index="0" value="chenheng1"/>
        <!--hobbyList-->
        <constructor-arg index="1">
            <list>
                <value>唱歌</value>
                <value>跳舞</value>
                <value>爬山</value>
            </list>
        </constructor-arg>
        <!--residenceMap  -->
        <constructor-arg index="2">
            <map>
                <entry key="dalian" value="大連"/>
                <entry key="beijing" value="北京"/>
                <entry key="shanghai" value="上海"/>
            </map>
        </constructor-arg>
        <!--aliasSet  -->
        <constructor-arg index="3">
            <set>
                <value>陳恒100</value>
                <value>陳恒101</value>
                <value>陳恒102</value>
            </set>
        </constructor-arg>
        <!--array  -->
        <constructor-arg index="4">
            <array>
                <value>aaaaa</value>
                <value>bbbbb</value>
            </array>
        </constructor-arg>
    </bean>
    
    
    <!--4.1.2 使用setter方法注入方式裝配 ComplexUser實例user2 -->
    <bean id="user2" class="assemble.ComplexUser">
        <property name="uname" value="chenheng2"/>
        <property name="hobbyList">
            <list>
                <value>看書</value>
                <value>學(xué)習(xí)Spring</value>
            </list>
        </property>
        <property name="residenceMap">
            <map>
                <entry key="shenzhen" value="深圳"/>
                <entry key="gaungzhou" value="廣州"/>
                <entry key="tianjin" value="天津"/>
            </map>
        </property>
        <property name="aliasSet">
            <set>
                <value>陳恒103</value>
                <value>陳恒104</value>
                <value>陳恒105</value>
            </set>
        </property>
        <property name="array">
            <array>
                <value>cccccc</value>
                <value>dddddd</value>
            </array>
        </property>
    </bean>
</beans>

ComplexUser.java

package assemble;
import java.util.List;
//4.1基于xml的裝配方式

import java.util.Map;
import java.util.Set;
public class ComplexUser {
    
    private String uname;
    private List<String> hobbyList;
    private Map<String,String> residenceMap;
    private Set<String> aliasSet;
    private String[] array;
    /*
     * 使用構(gòu)造方法注入,需要提供帶參數(shù)的構(gòu)造方法
     */
    public ComplexUser(String uname, List<String> hobbyList, Map<String, String> residenceMap, Set<String> aliasSet,
            String[] array) {
        super();
        this.uname = uname;
        this.hobbyList = hobbyList;
        this.residenceMap = residenceMap;
        this.aliasSet = aliasSet;
        this.array = array;
    }
    
    
    /*
     * 使用屬性的setter方法注入,提供默認無參數(shù)的構(gòu)造方法,并未住入的屬性提供setter方法
     */
    public ComplexUser() {
        super();
    }
    public void setUname(String uname) {
        this.uname = uname;
    }
    public void setHobbyList(List<String> hobbyList) {
        this.hobbyList = hobbyList;
    }
    public void setResidenceMap(Map<String, String> residenceMap) {
        this.residenceMap = residenceMap;
    }
    public void setAliasSet(Set<String> aliasSet) {
        this.aliasSet = aliasSet;
    }
    public void setArray(String[] array) {
        this.array = array;
    }
    @Override
    public String toString() {
        return "uname=" + uname + ";hobbyList =" + hobbyList + ";residenceMap=" 
    + residenceMap +";aliasSet=" + aliasSet + ";array=" + array;
    }
}

TestAssemble.java 測試

package test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import assemble.ComplexUser;
public class TestAssemble {
    public static void main(String[] args) {
        @SuppressWarnings("resource")
        ApplicationContext appCon = new ClassPathXmlApplicationContext("applicationContext.xml");
        //測試構(gòu)造方法裝配
        ComplexUser u1 = (ComplexUser)appCon.getBean("user1");
        System.out.println(u1);
        
        //測試setter方法注入
        ComplexUser u2 = (ComplexUser)appCon.getBean("user2");
        System.out.println(u2);
    }
}

2.基于注解的裝配方式

@Component
該注解是一個泛化的概念,僅僅表示一個組件對象(Bean),可以作用在任何層次上

AnnotationUser.java
package annotation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component()//相當于@Component("annotationUser")或者@Component(value = "annotationUser"),annotationUser為Bean的id,默認為首字母小寫的類名
public class AnnotationUser {
    @Value("chenheng")
    private String uname;
    
    public String getUname() {
        return uname;
    }
    public void setUname(String uname) {
        this.uname = uname;
    }
    @Override
    public String toString() {
        return "uname=" + uname;
    }
}
在annotationContext里面告訴Spring在哪掃描
<?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: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.xsd">
    <!-- 使用context命名空間,通過Spring掃描指定包下所有Bean的實現(xiàn)類,進行注解解析 -->
    <context:component-scan base-package="annotation"/>
</beans>

在TestAnnotation里面測試(注意這里要導(dǎo)入spring-aop-5.0.5.RELEASE.jar的包)

package test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import annotation.AnnotationUser;
public class TestAnnotation {
    public static void main(String[] args) {
        ApplicationContext appCon = new ClassPathXmlApplicationContext("annotationContext.xml");
        AnnotationUser au = (AnnotationUser)appCon.getBean("annotationUser");
        System.out.println(au.getUname());
    }
}

為了層次化:@Repository標注DAO層,@Service標注業(yè)務(wù)邏輯層、@Controller標注控制層
(1)創(chuàng)建dao層

package annotation.dao;
import org.springframework.stereotype.Repository;
@Repository("testDao")

public class TestDaoImpl implements TestDao{
    @Override
    public void save() {
        System.out.println("testDao save");
    }
}

(2)創(chuàng)建service層

package annotation.service;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import annotation.dao.TestDao;
@Service("testService")//????@Service
public class TestSeviceImpl implements TestService{
    @Resource(name="testDao")
    
    private TestDao testDao;
    @Override
    public void save() {
        testDao.save();
        System.out.println("testService save");
    }
}

(3)創(chuàng)建Controller層

package annotation.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import annotation.service.TestService;
@Controller
public class TestController {
    @Autowired
    private TestService testService;
    public void save() {
        testService.save();
        System.out.println("testController save");
    }
}

配置注解:
之前已經(jīng)配置過了(通過Spring掃描指定包下所有Bean的實現(xiàn)類)

<context:component-scan base-package="annotation"/>

創(chuàng)建測試類:

TestMoreAnnotation
package test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import annotation.controller.TestController;
public class TestMoreAnnotation {
    public static void main(String[] args) {
        ApplicationContext appCon = new ClassPathXmlApplicationContext("annotationContext.xml");
        TestController testcon = (TestController)appCon.getBean("testController"); 
        testcon.save();
    }
}
屏幕快照 2019-03-14 下午11.32.25.png

屏幕快照 2019-03-14 下午11.43.16.png

【四】遇到問題:

The import javax.servlet.annotation cannot be resolved

導(dǎo)入:servlet-api.jar包,然后在buildpath-addlibrary里面點擊runtimesever添加服務(wù)器

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容