3.5 Bean的裝配方式

Bean的裝配方式可以理解為將Bean依賴注入到Spring容器中,Bean的裝配方式即Bean的依賴注入方式。Spring容器支持基于XML配置的裝配、基于注解的裝配以及自動(dòng)裝配等多種裝配方式。本節(jié)將主要講解基于XML配置的裝配和基于注解的裝配。

1.基于XML配置的裝配

通過2.3節(jié)的學(xué)習(xí)之后,我們知道Spring提供了兩種基于XML配置的裝配方式:構(gòu)造方法注入和屬性setter方法注入。

目錄結(jié)構(gòu)

img

1.1創(chuàng)建Bean的實(shí)現(xiàn)類

在ch3應(yīng)用src目錄中,創(chuàng)建包assemble,在assemble包下創(chuàng)建類ComplexUser。在類ComplexUser中分別使用構(gòu)造方法注入和setter注入

ComplexUser.java

package assemble;

import java.util.Arrays;
import java.util.List;
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;
    
    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;
    }

    public ComplexUser() {
        super();
        // TODO Auto-generated constructor stub
    }

    public String getUname() {
        return uname;
    }

    public void setUname(String uname) {
        this.uname = uname;
    }

    public List<String> getHobbyList() {
        return hobbyList;
    }

    public void setHobbyList(List<String> hobbyList) {
        this.hobbyList = hobbyList;
    }

    public Map<String, String> getResidenceMap() {
        return residenceMap;
    }

    public void setResidenceMap(Map<String, String> residenceMap) {
        this.residenceMap = residenceMap;
    }

    public Set<String> getAliasSet() {
        return aliasSet;
    }

    public void setAliasSet(Set<String> aliasSet) {
        this.aliasSet = aliasSet;
    }

    public String[] getArray() {
        return array;
    }

    public void setArray(String[] array) {
        this.array = array;
    }

    @Override
    public String toString() {
        return "ComplexUser [uname=" + uname + ", hobbyList=" + hobbyList + ", residenceMap=" + residenceMap
                + ", aliasSet=" + aliasSet + ", array=" + Arrays.toString(array) + "]";
    }
    
    
}

1.2配置Bean

在Spring配置文件中,使用實(shí)現(xiàn)類ComplexUser配置Bean的兩個(gè)實(shí)例。

<!-- 使用構(gòu)造方法注入方式裝配ComplexUser實(shí)例user1 -->
    <bean id="user1" class="assemble.ComplexUser">
        <constructor-arg index="0" value="cxk" />
        <constructor-arg index="1">
            <list>
                <value>唱</value>
                <value>跳</value>
                <value>rap</value>
                <value>籃球</value>
            </list> 
        </constructor-arg>
        <constructor-arg index="2">
            <map>
                <entry key="dalian" value="大連" />
                <entry key="shenyang" value="沈陽" />
                <entry key="shanghia" value="上海" />
            </map>
        </constructor-arg>
        <constructor-arg index="3">
            <set>
                <value>100</value>
                <value>101</value>
                <value>102</value>
            </set>
        </constructor-arg>
        <constructor-arg index="4">
            <array>
                <value>aaaaa</value>
                <value>bbbbb</value>
            </array>
        </constructor-arg>
    </bean>
<!-- 使用屬性setter方法注入方式裝配ComplexUser實(shí)例user2 -->
    <bean id="user2" class="assemble.ComplexUser">
        <property name="uname" value="wtf" />
        <property name="hobbyList">
            <list>
                <value>看書</value>
                <value>學(xué)spring</value>
            </list> 
        </property>
        <property name="residenceMap">
            <map>
                <entry key="dalian" value="大連" />
                <entry key="shenyang" value="沈陽" />
                <entry key="shanghia" value="上海" />
            </map>
        </property>
        <property name="aliasSet">
            <set>
                <value>103</value>
                <value>104</value>
                <value>105</value>
            </set>
        </property>
        <property name="array">
            <array>
                <value>ccccc</value>
                <value>ddddd</value>
            </array>
        </property>
    </bean>

1.3測(cè)試基于XML配置的裝配方式

在ch3應(yīng)用的test包中,創(chuàng)建測(cè)試類TestAssemble

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) {
        // TODO Auto-generated method stub
        ApplicationContext appCon = new ClassPathXmlApplicationContext("applicationContext.xml");
        ComplexUser u1 = (ComplexUser)appCon.getBean("user1");
        System.out.println(u1);
        ComplexUser u2 = (ComplexUser)appCon.getBean("user2");
        System.out.println(u2);
    }

}

運(yùn)行結(jié)果

img

2.基于注解的裝配

在Spring框架中定義了一些列的注解,常用注解的使用見3.5+;
下面通過一個(gè)實(shí)例講解@Component()

注:在Spring 4.0以上版本,配置注解指定包中的注解進(jìn)行掃描前,需要事先導(dǎo)入Spring Aop的JAR包spring-aop-5.0.2.RELEASE.jar

目錄結(jié)構(gòu)

img

2.1創(chuàng)建Bean的實(shí)現(xiàn)類

在ch3應(yīng)用src目錄中,創(chuàng)建包annotation,在annotation包下創(chuàng)建類AnnotationUser.java。

AnnotationUser.java

package annotation;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component()
/*
 * 相當(dāng)于@Component("annotationUser")或
 * @Component(value="annotationUser"),annotationUser為Bean的id,默認(rèn)為類名首字母的小寫
 */
public class AnnotationUser {
    @Value("基于注解裝配")
    private String uname;

    public String getUname() {
        return uname;
    }

    public void setUname(String uname) {
        this.uname = uname;
    }

    @Override
    public String toString() {
        return "AnnotationUser [uname=" + uname + "]";
    }
    
    
}

2.2配置注解

現(xiàn)在有了Bean的實(shí)現(xiàn)類,但還不能進(jìn)行測(cè)試,因?yàn)镾pring容器并不知道去哪里掃描Bean對(duì)象。需要在配置文件中配置注解,這里我們?cè)趕rc目錄中新建一個(gè)annotationContext.xml,注解配置方式如下:

annotationContext.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: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實(shí)現(xiàn)類,通過注釋解析 -->
    <context:component-scan base-package="annotation"/>
     
</beans>

2.3測(cè)試Bean實(shí)例

在ch3英語的test包中,創(chuàng)建測(cè)試類TestAnnotation,具體代碼如下

TestAnnotation.java

package test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import annotation.AnnotationUser;
import assemble.ComplexUser;

public class TestAnnotation {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ApplicationContext appCon = new ClassPathXmlApplicationContext("annotationContext.xml");
        AnnotationUser au = (AnnotationUser)appCon.getBean("annotationUser");
        System.out.println(au.getUname());
    }

}

運(yùn)行結(jié)果

img

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

相關(guān)閱讀更多精彩內(nèi)容

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