1. 程式人生 > >Spring的《XML顯式裝配bean》- 注入List或則set

Spring的《XML顯式裝配bean》- 注入List或則set

這一節主要講解spring注入list或則set型別的屬性

本blog舉的例子是:不同的廚師使用不同個烤爐製作出不同的蛋糕。

(1)domain
蛋糕類:

package spring.ch1.topic11;

/**
 * Created by louyuting on 17/1/20.
 * 注入屬性,記得屬性必須要寫setter方法  不然就會丟擲異常,注入失敗.
 * 蛋糕類
 */
public class Cake {
    private static int index = 0;

    private final int id = index++;

    private
String name = ""; private double size = 0; public String getName() { return name; } public void setName(String name) { this.name = name; } public double getSize() { return size; } public void setSize(double size) { this.size = size; } public
int getId() { return id; } @Override public String toString() { return "create the cake,its id:" + id + ", size:" + size + " inch ,name:" + name; } }

廚師類:

package spring.ch1.topic11;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

/**
 * Created by louyuting on 17/1/20.
 * 廚師類
 */
public class Chief { private static int index = 0; private List<Cake> cakes = null; private final int id = index++; private String name = ""; private HashSet<Oven> ovens = null; public List<Cake> getCakes() { return cakes; } public int getId() { return id; } public String getName() { return name; } public HashSet<Oven> getOvens() { return ovens; } public void setCakes(List<Cake> cakes) { this.cakes = cakes; } public void setName(String name) { this.name = name; } public void setOvens(HashSet<Oven> ovens) { this.ovens = ovens; } public List<Cake> makeCakes() { for (Iterator<Cake> iterator = cakes.iterator(); iterator.hasNext();) { Cake cake = iterator.next(); System.out.println(name + ": " + cake); } return getCakes(); } public void userOvens() { for (Iterator<Oven> iterator = ovens.iterator(); iterator.hasNext();) { Oven oven = iterator.next(); System.out.println("use " + oven); } } }

廚師類這裡需要解釋一下:
(1)為了使用不同的烤爐,我們加入了ovens,由於實際情況當中只有大小烤爐各一個,所以我們這裡只是使用set,而不是使用list

(2)為了能夠做出不同的蛋糕,我們使用一個list來放置不同的蛋糕,而這裡允許重複,因此這裡使用list

(3)為了輸出方便,我在userOvens和makeCakes裡面直接輸出資料

烤爐類:

package spring.ch1.topic11;

/**
 * Created by louyuting on 17/1/21.
 * 烤爐類
 */
public class Oven {
    private String name = "";

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

(2)配置檔案:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--scope預設是單例的-->
    <bean id="blueberryCheeseCake"
          class="spring.ch1.topic11.Cake"
          scope="prototype">
        <property name="name" value="blueberry cheese cake"/>
        <property name="size" value="5.0"/>
    </bean>

    <bean id="chocolateCheeseCake"
          class="spring.ch1.topic11.Cake"
          scope="prototype">
        <property name="name" value="chocolate cheese cake"/>
        <property name="size" value="6.0"/>
    </bean>

    <bean id="bananaAatmelMousseCake"
          class="spring.ch1.topic11.Cake"
          p:name="banana oatmel mousse cake" p:size="7"
          scope="prototype">
    </bean>

    <bean id="vanillaEclair"
          class="spring.ch1.topic11.Cake"
          p:name="vanilla eclair" p:size="8"
          scope="prototype">
    </bean>

    <bean id="ligueurPerfumedTripletCake"
          class="spring.ch1.topic11.Cake"
          p:name="ligueur perfumed triplet cake" p:size="5.5"
          scope="prototype">
    </bean>

    <bean id="bigOven"
          class="spring.ch1.topic11.Oven"
          p:name="bigOven"
          scope="singleton">
    </bean>

    <bean id="smallOven"
          class="spring.ch1.topic11.Oven"
          p:name="smallOven"
          scope="singleton">
    </bean>

    <bean id="jack" class="spring.ch1.topic11.Chief" p:name="jack">
        <property name="ovens">
            <set>
                <ref bean="bigOven"/>
                <ref bean="bigOven"/>
                <ref bean="smallOven"/>
            </set>
        </property>
        <property name="cakes">
            <list>
                <ref bean="blueberryCheeseCake" />
                <ref bean="chocolateCheeseCake" />
                <ref bean="bananaAatmelMousseCake" />
                <ref bean="vanillaEclair" />
            </list>
        </property>
    </bean>

    <bean id="rose" class="spring.ch1.topic11.Chief" p:name="rose">
        <property name="ovens">
            <set>
                <ref bean="smallOven"/>
            </set>
        </property>
        <property name="cakes">
            <list>
                <ref bean="vanillaEclair" />
                <ref bean="ligueurPerfumedTripletCake" />
                <ref bean="chocolateCheeseCake" />
            </list>
        </property>
    </bean>

</beans>

需要解釋一下的地方:
(1)我們利用一個蛋糕類,通過名稱等屬性的變化,來建立不同類別的蛋糕物件

(2)我們利用一個烤爐類,通過名稱等屬性的變化,來建立不同類別的烤爐物件

(3)我們利用一個廚師類,通過名稱等屬性的變化,來建立不同類別的廚師物件

注:上面這幾點比較能夠體現程式碼的複用

(4)每個蛋糕Bean都需要使用prototype的作用域,這樣才能夠每次建立的都是不同的蛋糕物件,不然後面get蛋糕的時候就會出現兩個相同id的蛋糕,這個明顯是不符合實際情況的。

(5)但是烤爐的情況不一樣,由於對於麵包鋪來說,烤爐的數量是一定的,不能夠出現多個烤爐,因此他們必須使用預設的單例模式

(6)配置廚師裡面的烤爐屬性時,我們使用了set,這樣即便像上面配置多了,也不會重複出現,因為這個collection具備了set的特性;而配置蛋糕屬性的時候我們使用list,由於每一個蛋糕都不一樣,因此使用list比較合適

(7)list和set除了上面的能夠放入Bean之外,還可以放入value,這個時候只需要使用標籤即可,不是使用,但是由於注入值比較少,因此不作詳細說明。

(3)測試類:

package spring.ch1.topic11;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * Created by louyuting on 17/1/20.
 * 注入List和Set
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/spring/ch1/topic11/ApplicationContext-test.xml"})
public class ChiefTest {
    @Autowired
    private ApplicationContext applicationContext;

    @Test
    public void testChief(){
        Chief jack = (Chief)applicationContext.getBean("jack");
        jack.userOvens();
        jack.makeCakes();
        Chief rose = (Chief)applicationContext.getBean("rose");
        rose.userOvens();
        rose.makeCakes();
    }
}

從容器裡面取出不同的廚師物件,然後廚師就開始使用烤爐製作蛋糕。
(4)輸出結果:

/**
use bigOven
use smallOven
jack: create the cake,its id:0, size:5.0 inch ,name:blueberry cheese cake
jack: create the cake,its id:1, size:6.0 inch ,name:chocolate cheese cake
jack: create the cake,its id:2, size:7.0 inch ,name:banana oatmel mousse cake
jack: create the cake,its id:3, size:8.0 inch ,name:vanilla eclair
use smallOven
rose: create the cake,its id:4, size:8.0 inch ,name:vanilla eclair
rose: create the cake,its id:5, size:5.5 inch ,name:ligueur perfumed triplet cake
rose: create the cake,its id:6, size:6.0 inch ,name:chocolate cheese cake
*/

相關推薦

Spring的《XML裝配bean》- 注入Listset

這一節主要講解spring注入list或則set型別的屬性 本blog舉的例子是:不同的廚師使用不同個烤爐製作出不同的蛋糕。 (1)domain 蛋糕類: package spring.ch1.topic11; /** * Created

Spring的《XML裝配bean》之通過構造器注入Bean

本文主要講解兩點: 1.怎麼樣宣告一個bean 2.通過構造器注入bean 1. 怎麼樣宣告一個bean? 1) 建立一個類: package spring.ch1.topic5; public class Song {

在IoC容器中裝配Bean之-----------基於XML的配置(依賴注入)

一.Spring裝配Bean的簡要概述 1.要使應用程式中的Spring容器成功啟動, 需要同時具備以下三個方面的條件: (1)Spring框架的類包都已經被Maven專案依賴成功. (2)應用程式為Spring提供了完整的Bean配置資訊. (3)Bean的類都已經

Spring中隱bean發現機制和自動裝配

儘管Spring的配置風格是可以互相搭配的,但是應該儘可能的使用自動配置的機制,顯式配置越少越好 Spring從兩個角度來實現自動化裝配: 元件掃描:Spring會自動發現應用上下文中所建立的bean 自動裝配:Spring會自動滿足bean之間的依賴

Spring 中如何向 Bean 注入系統屬性環境變數

在 Spring 中為 javabean 注入屬性檔案中的屬性值一般人都知道的,可以通過 org.springframework.beans.factory.config.PropertyPlaceholderConfigurer 引入一個屬性檔案,然後給 bean 指定

Spring 裝配Bean的構造注入

在spring裝配bean中還有一種Set注入的替代,那就是構造引數的注入。 set注入是一種直接方式,缺點是它假設了所 有的可變屬性都可以通過set方法訪問到。例如有些屬性在建立時設定一次,以後不再改變。替代方式是通過建構函式設定一些屬性值。還有它無法清晰表

深入學習Spring框架之二構造器注入方式裝配Bean

    這一節我們來看看怎麼使用Spring建立我們的Bean物件。     容器是Spring的核心,Spring的容器有兩種型別:Bean工廠,由BeanFactory介面定義,是最簡單的容器;以及應用上下文,由ApplicationContext定義。Bean工廠對於

spring裝配bean及引數注入

個人使用建議:不要使用3.2.4版本  因為在進行xml檔案載入的時候會出錯。 首先搭建環境 Student.java package com.demo.entity; public class Student { private String name;

Spring4 實戰筆記(1):裝配bean—依賴注入的本質

這種字串形式的表示雖然可以,但是不具備“型別安全”,因此Spring也提供了更加型別安全的機制,即通過類或者介面來設定掃描機制的目標目錄,例如: @Configuration @ComponentScan(basePackageClasses = {CDPlayer.class, DVDPlayer.cl

程式碼注入Spring ApplicationContext說明。

一、簡單的用ApplicationContext做測試的話,獲得Spring中定義的Bean例項(物件).可以用: ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext

C# 關鍵字explicit(顯示),implicit(隱),類型的隱轉換

tar oid bsp color col 必須 code 類型 顯示 class Program { static void Main(string[] args) { Adaptee ada = ne

Spring裝配bean--02通過Java代碼裝配bean

三方 應用 context his 單獨 stc ring -- oid Spring容器負責創建應用程序中的bean並通過DI來協調這些對象之間的關系 Spring提供了三種主要的裝配機制: 在XML中進行顯式配置 在Java中進行顯式配置 隱式

python筆記10-切片(從list字符串中取幾個元素)

-1 下標 功能 切片 name 字符 list python 筆記 name1 = ‘zcl,pyzyz‘names = [‘zcl‘,‘py‘,‘zyz‘]#切片的意思就是從list裏面或者字符串裏面取幾個元素#切片操作對字符串也是完全適用的# print(names[

接口實現

不同 face 顯式 函數 對象 blog 簽名 string 有時 一個類實現的多個接口裏面有相同函數,而多個接口裏的相同簽名函數確實需要不同的實現,此情況下可以用顯示接口避免。 兩點註意:需要加接口名限定前綴,不需要加public修飾符,因為顯式接口成員只能通過接口來

在IOC中裝配Bean

ioc bean一、基於XML的配置 采用Schema格式<?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.springframework.org/schema/beans"//默認命名空間,用於bean的定義

Spring學習系列(二) 自動化裝配Bean

can one bean 工作 顯式 實例 cnblogs con frame 一、Spring裝配-自動化裝配 @[email protected]/* */ 通過spring註解(@Component)來表明該類會作為組件類,並告知Spring要為這類創建b

selenium python 和隱等待方法

http load python exe keys users ive 匿名函數 間隙 1 # -*- coding:utf-8 -*- 2 from selenium import webdriver 3 from selenium.webdriver.commo

intent和隱intent

this .text 接收 Coding 南京 聲明 menuitem ret 處理 android其中顯式intent和隱式intent的差別 定義:   Intent定義:Intent是一種在不同組件之間傳遞的請求消息。是應用程序發出的請求和意圖。作為一個完

轉換和轉換

string 運算 依次 col 指向 pri ast 現象 style C/C++對於數據類型的轉換包括隱式轉換和顯式轉換(強制類型轉換)。 一般來說,隱式轉換包括以下幾種情形: 1. 低精度與高精度混合運算,低精度會隱式轉換成高精度類型。 int a = 10; do

一次GC導致的High CPU問題處理過程

.cn images 雲服務 obj 日誌 驚人的 什麽 cati ros 項目現場反饋系統出現性能問題,具體表現為:所有的客戶端響應極其卡頓。 第一反應推測,難道是DB層面出現阻塞?檢查v$session會話狀態及等待類型未見異常,應該可以排除DB層面原因導致的可能。 繼