国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Spring IOC基于XML和注解管理Bean(一)

這篇具有很好參考價(jià)值的文章主要介紹了Spring IOC基于XML和注解管理Bean(一)。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問(wèn)。

Spring IOC基于XML和注解管理Bean(二)


IoC 是 Inversion of Control 的簡(jiǎn)寫,譯為“ 控制反轉(zhuǎn) ”,它不是一門技術(shù),而是一種設(shè)計(jì)思想,是一個(gè)重要的面向?qū)ο缶幊谭▌t,能夠指導(dǎo)我們?nèi)绾卧O(shè)計(jì)出 松耦合、更優(yōu)良的程序。

Spring 通過(guò) IoC 容器來(lái)管理所有 Java 對(duì)象的實(shí)例化和初始化,控制對(duì)象與對(duì)象之間的依賴關(guān)系。將由 IoC 容器管理的 Java 對(duì)象稱為 Spring Bean,它與使用關(guān)鍵字 new 創(chuàng)建的 Java 對(duì)象沒(méi)有任何區(qū)別。

IoC 容器是 Spring 框架中最重要的核心組件之一,它貫穿了 Spring 從誕生到成長(zhǎng)的整個(gè)過(guò)程。

1、IoC容器

1.1、控制反轉(zhuǎn)(IoC)

  • 控制反轉(zhuǎn)是一種思想。

  • 控制反轉(zhuǎn)是為了降低程序耦合度,提高程序擴(kuò)展力。

  • 控制反轉(zhuǎn),反轉(zhuǎn)的是什么?

    • 將對(duì)象的創(chuàng)建權(quán)利交出去,交給第三方容器負(fù)責(zé)
    • 將對(duì)象和對(duì)象之間關(guān)系的維護(hù)權(quán)交出去,交給第三方容器負(fù)責(zé)。
  • 控制反轉(zhuǎn)這種思想如何實(shí)現(xiàn)呢?

    • DI(Dependency Injection):依賴注入

1.2、依賴注入

DI(Dependency Injection):依賴注入,依賴注入實(shí)現(xiàn)了控制反轉(zhuǎn)的思想。

依賴注入:

  • 指Spring創(chuàng)建對(duì)象的過(guò)程中,將對(duì)象依賴屬性通過(guò)配置進(jìn)行注入

依賴注入常見(jiàn)的實(shí)現(xiàn)方式包括兩種:

  • 第一種:set注入
  • 第二種:構(gòu)造注入

所以結(jié)論是:IOC 就是一種控制反轉(zhuǎn)的思想, 而 DI 是對(duì)IoC的一種具體實(shí)現(xiàn)。

Bean管理的是:Bean對(duì)象的創(chuàng)建,以及Bean對(duì)象中屬性的賦值(或者叫做Bean對(duì)象之間關(guān)系的維護(hù))。

1.3、IoC容器在Spring的實(shí)現(xiàn)

Spring 的 IoC 容器就是 IoC思想的一個(gè)落地的產(chǎn)品實(shí)現(xiàn)。IoC容器中管理的組件也叫做 bean。在創(chuàng)建 bean 之前,首先需要?jiǎng)?chuàng)建IoC 容器。Spring 提供了IoC 容器的兩種實(shí)現(xiàn)方式:

BeanFactory

這是 IoC 容器的基本實(shí)現(xiàn),是 Spring 內(nèi)部使用的接口。面向 Spring 本身,不提供給開(kāi)發(fā)人員使用。

ApplicationContext

BeanFactory 的子接口,提供了更多高級(jí)特性。面向 Spring 的使用者,幾乎所有場(chǎng)合都使用 ApplicationContext 而不是底層的 BeanFactory。

ApplicationContext的主要實(shí)現(xiàn)類

Spring IOC基于XML和注解管理Bean(一)

類型名 簡(jiǎn)介
ClassPathXmlApplicationContext 通過(guò)讀取類路徑下的 XML 格式的配置文件創(chuàng)建 IOC 容器對(duì)象
FileSystemXmlApplicationContext 通過(guò)文件系統(tǒng)路徑讀取 XML 格式的配置文件創(chuàng)建 IOC 容器對(duì)象
ConfigurableApplicationContext ApplicationContext 的子接口,包含一些擴(kuò)展方法 refresh() 和 close() ,讓 ApplicationContext 具有啟動(dòng)、關(guān)閉和刷新上下文的能力。
WebApplicationContext 專門為 Web 應(yīng)用準(zhǔn)備,基于 Web 環(huán)境創(chuàng)建 IOC 容器對(duì)象,并將對(duì)象引入存入 ServletContext 域中。

2、基于XML管理Bean

2.1、搭建模塊spring-first

①搭建模塊

模塊:spring-first

②添加依賴

<dependencies>
    <!--spring context依賴-->
    <!--當(dāng)你引入Spring Context依賴之后,表示將Spring的基礎(chǔ)依賴引入了-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>6.0.3</version>
    </dependency>

    <!--junit5測(cè)試-->
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>5.3.1</version>
    </dependency>

    <!--log4j2的依賴-->
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.19.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-slf4j2-impl</artifactId>
        <version>2.19.0</version>
    </dependency>
</dependencies>

③引入配置文件

引入spring-first模塊配置文件:beans.xml、log4j2.xml

beans.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="helloWorld" class="org.example.bean.HelloWorld"></bean>

</beans>

log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <loggers>
        <!--
            level指定日志級(jí)別,從低到高的優(yōu)先級(jí):
                TRACE < DEBUG < INFO < WARN < ERROR < FATAL
                trace:追蹤,是最低的日志級(jí)別,相當(dāng)于追蹤程序的執(zhí)行
                debug:調(diào)試,一般在開(kāi)發(fā)中,都將其設(shè)置為最低的日志級(jí)別
                info:信息,輸出重要的信息,使用較多
                warn:警告,輸出警告的信息
                error:錯(cuò)誤,輸出錯(cuò)誤信息
                fatal:嚴(yán)重錯(cuò)誤
        -->
        <root level="DEBUG">
            <appender-ref ref="spring6log"/>
            <appender-ref ref="RollingFile"/>
            <appender-ref ref="log"/>
        </root>
    </loggers>

    <appenders>
        <!--輸出日志信息到控制臺(tái)-->
        <console name="spring6log" target="SYSTEM_OUT">
            <!--控制日志輸出的格式-->
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss SSS} [%t] %-3level %logger{1024} - %msg%n"/>
        </console>

        <!--文件會(huì)打印出所有信息,這個(gè)log每次運(yùn)行程序會(huì)自動(dòng)清空,由append屬性決定,適合臨時(shí)測(cè)試用-->
        <File name="log" fileName="E:/Java/logs/test.log" append="false">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>
        </File>

        <!-- 這個(gè)會(huì)打印出所有的信息,
            每次大小超過(guò)size,
            則這size大小的日志會(huì)自動(dòng)存入按年份-月份建立的文件夾下面并進(jìn)行壓縮,
            作為存檔-->
        <RollingFile name="RollingFile" fileName="E:/Java/logs/app.log"
                     filePattern="log/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
            <PatternLayout pattern="%d{yyyy-MM-dd 'at' HH:mm:ss z} %-5level %class{36} %L %M - %msg%xEx%n"/>
            <SizeBasedTriggeringPolicy size="50MB"/>
            <!-- DefaultRolloverStrategy屬性如不設(shè)置,
            則默認(rèn)為最多同一文件夾下7個(gè)文件,這里設(shè)置了20 -->
            <DefaultRolloverStrategy max="20"/>
        </RollingFile>
    </appenders>
</configuration>

④引入java類

引入spring-first模塊java及test目錄下測(cè)試類

package org.example.bean;

public class HelloWorld {

    public HelloWorld() {
        System.out.println("無(wú)參數(shù)構(gòu)造方法執(zhí)行");
    }

    public void sayHello(){
        System.out.println("helloworld");
    }
}

package org.example.bean;

import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class HelloWorldTest {

    private Logger logger = LoggerFactory.getLogger(HelloWorldTest.class);

    @Test
    public void testHelloWorld(){
        
    }
}

2.2、實(shí)驗(yàn)一:獲取bean

①方式一:根據(jù)id獲取

由于 id 屬性指定了 bean 的唯一標(biāo)識(shí),所以根據(jù) bean 標(biāo)簽的 id 屬性可以精確獲取到一個(gè)組件對(duì)象。

@Test
public void testHelloWorld1(){
    ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
    HelloWorld helloworld = (HelloWorld) ac.getBean("helloWorld");
    helloworld.sayHello();
    logger.info("執(zhí)行成功");
}
②方式二:根據(jù)類型獲取
@Test
public void testHelloWorld1(){
    ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
    HelloWorld bean = ac.getBean(HelloWorld.class);
    bean.sayHello();
}
③方式三:根據(jù)id和類型
@Test
public void testHelloWorld2(){
    ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
    HelloWorld bean = ac.getBean("helloWorld", HelloWorld.class);
    bean.sayHello();
}
④注意的地方

當(dāng)根據(jù)類型獲取bean時(shí),要求IOC容器中指定類型的bean有且只能有一個(gè)

當(dāng)IOC容器中一共配置了兩個(gè):

<bean id="helloworldOne" class="org.example.bean.HelloWorld"></bean>
<bean id="helloworldTwo" class="org.example.bean.HelloWorld"></bean>

根據(jù)類型獲取時(shí)會(huì)拋出異常:

org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type ‘org.example.bean.HelloWorld’ available: expected single matching bean but found 2: helloworldOne,helloworldTwo

⑤擴(kuò)展知識(shí)

如果組件類實(shí)現(xiàn)了接口,根據(jù)接口類型可以獲取 bean 嗎?

可以,前提是bean唯一

如果一個(gè)接口有多個(gè)實(shí)現(xiàn)類,這些實(shí)現(xiàn)類都配置了 bean,根據(jù)接口類型可以獲取 bean 嗎?

不行,因?yàn)閎ean不唯一

結(jié)論

根據(jù)類型來(lái)獲取bean時(shí),在滿足bean唯一性的前提下,其實(shí)只是看:『對(duì)象 instanceof 指定的類型』的返回結(jié)果,只要返回的是true就可以認(rèn)定為和類型匹配,能夠獲取到。

java中,instanceof運(yùn)算符用于判斷前面的對(duì)象是否是后面的類,或其子類、實(shí)現(xiàn)類的實(shí)例。如果是返回true,否則返回false。也就是說(shuō):用instanceof關(guān)鍵字做判斷時(shí), instanceof 操作符的左右操作必須有繼承或?qū)崿F(xiàn)關(guān)系

2.3、實(shí)驗(yàn)二:依賴注入之setter注入

①創(chuàng)建學(xué)生類Student

package org.example.bean;

public class Student {

    private Integer id;

    private String name;

    private Integer age;

    private String sex;

    public Student() {
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                '}';
    }

}

②配置bean時(shí)為屬性賦值

spring-di.xml

<bean id="studentOne" class="org.example.bean.Student">
    <!-- property標(biāo)簽:通過(guò)組件類的setXxx()方法給組件對(duì)象設(shè)置屬性 -->
    <!-- name屬性:指定屬性名(這個(gè)屬性名是getXxx()、setXxx()方法定義的,和成員變量無(wú)關(guān)) -->
    <!-- value屬性:指定屬性值 -->
    <property name="id" value="1001"></property>
    <property name="name" value="張三"></property>
    <property name="age" value="23"></property>
    <property name="sex" value=""></property>
</bean>

③測(cè)試

@Test
public void testDIBySet(){
    ApplicationContext ac = new ClassPathXmlApplicationContext("spring-di.xml");
    Student studentOne = ac.getBean("studentOne", Student.class);
    System.out.println(studentOne);
}

2.4、實(shí)驗(yàn)三:依賴注入之構(gòu)造器注入

①在Student類中添加有參構(gòu)造

public Student(Integer id, String name, Integer age, String sex) {
    this.id = id;
    this.name = name;
    this.age = age;
    this.sex = sex;
}

②配置bean

spring-di.xml

<bean id="studentTwo" class="org.example.bean.Student">
    <constructor-arg value="1002"></constructor-arg>
    <constructor-arg value="李四"></constructor-arg>
    <constructor-arg value="33"></constructor-arg>
    <constructor-arg value=""></constructor-arg>
</bean>

注意:

constructor-arg標(biāo)簽還有兩個(gè)屬性可以進(jìn)一步描述構(gòu)造器參數(shù):

  • index屬性:指定參數(shù)所在位置的索引(從0開(kāi)始)
  • name屬性:指定參數(shù)名

③測(cè)試

@Test
public void testDIByConstructor(){
    ApplicationContext ac = new ClassPathXmlApplicationContext("spring-di.xml");
    Student studentOne = ac.getBean("studentTwo", Student.class);
    System.out.println(studentOne);
}

2.5、實(shí)驗(yàn)四:特殊值處理

①字面量賦值

什么是字面量?

int a = 10;

聲明一個(gè)變量a,初始化為10,此時(shí)a就不代表字母a了,而是作為一個(gè)變量的名字。當(dāng)我們引用a的時(shí)候,我們實(shí)際上拿到的值是10。

而如果a是帶引號(hào)的:‘a(chǎn)’,那么它現(xiàn)在不是一個(gè)變量,它就是代表a這個(gè)字母本身,這就是字面量。所以字面量沒(méi)有引申含義,就是我們看到的這個(gè)數(shù)據(jù)本身。

<!-- 使用value屬性給bean的屬性賦值時(shí),Spring會(huì)把value屬性的值看做字面量 -->
<property name="name" value="張三"/>
②null值
<property name="name">
    <null />
</property>

注意:

<property name="name" value="null"></property>

以上寫法,為name所賦的值是字符串null

③xml實(shí)體

XML實(shí)體是在XML文檔中使用的特殊字符序列。它們用于表示一些特殊的字符或符號(hào),例如小于號(hào)(<)或商標(biāo)符號(hào)(?),這些字符在XML語(yǔ)法中具有特殊含義。如果不使用實(shí)體,這些字符可能會(huì)被解釋為XML標(biāo)記,從而導(dǎo)致XML解析錯(cuò)誤。因此,實(shí)體允許在XML文檔中使用這些特殊字符而不會(huì)影響文檔的語(yǔ)法。

<!-- 小于號(hào)在XML文檔中用來(lái)定義標(biāo)簽的開(kāi)始,不能隨便使用 -->
<!-- 解決方案一:使用XML實(shí)體來(lái)代替 -->
<property name="expression" value="a &lt; b"/>
④CDATA節(jié)

CDATA節(jié)是XML文檔中的一種特殊標(biāo)記,用于表示包含非XML數(shù)據(jù)的文本。CDATA節(jié)中的文本內(nèi)容不會(huì)被解析器解析為XML元素或?qū)嶓w,而是原樣輸出,可以包含任何字符,包括特殊字符和標(biāo)記符號(hào)。CDATA節(jié)可以用于嵌入腳本、樣式表、HTML代碼等非XML數(shù)據(jù)。語(yǔ)法格式為<![CDATA[...]]>。

<property name="expression">
    <!-- 解決方案二:使用CDATA節(jié) -->
    <!-- CDATA中的C代表Character,是文本、字符的含義,CDATA就表示純文本數(shù)據(jù) -->
    <!-- XML解析器看到CDATA節(jié)就知道這里是純文本,就不會(huì)當(dāng)作XML標(biāo)簽或?qū)傩詠?lái)解析 -->
    <!-- 所以CDATA節(jié)中寫什么符號(hào)都隨意 -->
    <value><![CDATA[a < b]]></value>
</property>

2.6、實(shí)驗(yàn)五:為對(duì)象類型屬性賦值

①創(chuàng)建班級(jí)類Clazz

package org.example.bean;
    
public class Clazz {

    private Integer clazzId;

    private String clazzName;

    public Integer getClazzId() {
        return clazzId;
    }

    public void setClazzId(Integer clazzId) {
        this.clazzId = clazzId;
    }

    public String getClazzName() {
        return clazzName;
    }

    public void setClazzName(String clazzName) {
        this.clazzName = clazzName;
    }

    @Override
    public String toString() {
        return "Clazz{" +
                "clazzId=" + clazzId +
                ", clazzName='" + clazzName + '\'' +
                '}';
    }

    public Clazz() {
    }

    public Clazz(Integer clazzId, String clazzName) {
        this.clazzId = clazzId;
        this.clazzName = clazzName;
    }
}

②修改Student類

在Student類中添加以下代碼:

private Clazz clazz;

public Clazz getClazz() {
	return clazz;
}

public void setClazz(Clazz clazz) {
	this.clazz = clazz;
}
方式一:引用外部bean

配置Clazz類型的bean:

<bean id="clazzOne" class="org.example.bean.Clazz">
    <property name="clazzId" value="1111"></property>
    <property name="clazzName" value="財(cái)源滾滾班"></property>
</bean>

為Student中的clazz屬性賦值:

<bean id="studentFour" class="org.example.bean.Student">
    <property name="id" value="1004"></property>
    <property name="name" value="趙六"></property>
    <property name="age" value="26"></property>
    <property name="sex" value=""></property>
    <!-- ref屬性:引用IOC容器中某個(gè)bean的id,將所對(duì)應(yīng)的bean為屬性賦值 -->
    <property name="clazz" ref="clazzOne"></property>
</bean>

錯(cuò)誤演示:

<bean id="studentFour" class="org.example.bean.Student">
    <property name="id" value="1004"></property>
    <property name="name" value="趙六"></property>
    <property name="age" value="26"></property>
    <property name="sex" value=""></property>
    <property name="clazz" value="clazzOne"></property>
</bean>

如果錯(cuò)把ref屬性寫成了value屬性,會(huì)拋出異常: Caused by: java.lang.IllegalStateException: Cannot convert value of type ‘java.lang.String’ to required type ‘org.example.bean.Clazz’ for property ‘clazz’: no matching editors or conversion strategy found

意思是不能把String類型轉(zhuǎn)換成我們要的Clazz類型,說(shuō)明我們使用value屬性時(shí),Spring只把這個(gè)屬性看做一個(gè)普通的字符串,不會(huì)認(rèn)為這是一個(gè)bean的id,更不會(huì)根據(jù)它去找到bean來(lái)賦值

方式二:內(nèi)部bean
<bean id="studentFour" class="org.example.bean.Student">
    <property name="id" value="1004"></property>
    <property name="name" value="趙六"></property>
    <property name="age" value="26"></property>
    <property name="sex" value=""></property>
    <property name="clazz">
        <!-- 在一個(gè)bean中再聲明一個(gè)bean就是內(nèi)部bean -->
        <!-- 內(nèi)部bean只能用于給屬性賦值,不能在外部通過(guò)IOC容器獲取,因此可以省略id屬性 -->
        <bean id="clazzInner" class="org.example.bean.Clazz">
            <property name="clazzId" value="2222"></property>
            <property name="clazzName" value="遠(yuǎn)大前程班"></property>
        </bean>
    </property>
</bean>
方式三:級(jí)聯(lián)屬性賦值
<bean id="studentFour" class="org.example.bean.Student">
    <property name="id" value="1004"></property>
    <property name="name" value="趙六"></property>
    <property name="age" value="26"></property>
    <property name="sex" value=""></property>
    <property name="clazz" ref="clazzOne"></property>
    <property name="clazz.clazzId" value="3333"></property>
    <property name="clazz.clazzName" value="最強(qiáng)王者班"></property>
</bean>

2.7、實(shí)驗(yàn)六:為數(shù)組類型屬性賦值

①修改Student類

在Student類中添加以下代碼:

private String[] hobbies;

public String[] getHobbies() {
    return hobbies;
}

public void setHobbies(String[] hobbies) {
    this.hobbies = hobbies;
}

②配置bean

<bean id="studentFour" class="org.example.bean.Student">
    <property name="id" value="1004"></property>
    <property name="name" value="趙六"></property>
    <property name="age" value="26"></property>
    <property name="sex" value=""></property>
    <!-- ref屬性:引用IOC容器中某個(gè)bean的id,將所對(duì)應(yīng)的bean為屬性賦值 -->
    <property name="clazz" ref="clazzOne"></property>
    <property name="hobbies">
        <array>
            <value>吃飯</value>
            <value>睡覺(jué)</value>
            <value>打豆豆</value>
        </array>
    </property>
</bean>

2.8、實(shí)驗(yàn)七:為集合類型屬性賦值

①為L(zhǎng)ist集合類型屬性賦值

在Clazz類中添加以下代碼:

private List<Student> students;

public List<Student> getStudents() {
    return students;
}

public void setStudents(List<Student> students) {
    this.students = students;
}

配置bean:

<bean id="clazzTwo" class="org.example.bean.Clazz">
    <property name="clazzId" value="4444"></property>
    <property name="clazzName" value="Javaee0222"></property>
    <property name="students">
        <list>
            <ref bean="studentOne"></ref>
            <ref bean="studentTwo"></ref>
            <ref bean="studentThree"></ref>
        </list>
    </property>
</bean>

若為Set集合類型屬性賦值,只需要將其中的list標(biāo)簽改為set標(biāo)簽即可
若集合中是String類型,使用<value>吃飯</value>標(biāo)簽賦值即可

②為Map集合類型屬性賦值

創(chuàng)建教師類Teacher:

package org.example.bean;
public class Teacher {

    private Integer teacherId;

    private String teacherName;

    public Integer getTeacherId() {
        return teacherId;
    }

    public void setTeacherId(Integer teacherId) {
        this.teacherId = teacherId;
    }

    public String getTeacherName() {
        return teacherName;
    }

    public void setTeacherName(String teacherName) {
        this.teacherName = teacherName;
    }

    public Teacher(Integer teacherId, String teacherName) {
        this.teacherId = teacherId;
        this.teacherName = teacherName;
    }

    public Teacher() {

    }
    
    @Override
    public String toString() {
        return "Teacher{" +
                "teacherId=" + teacherId +
                ", teacherName='" + teacherName + '\'' +
                '}';
    }
}

在Student類中添加以下代碼:

private Map<String, Teacher> teacherMap;

public Map<String, Teacher> getTeacherMap() {
    return teacherMap;
}

public void setTeacherMap(Map<String, Teacher> teacherMap) {
    this.teacherMap = teacherMap;
}

配置bean:

<bean id="teacherOne" class="org.example.bean.Teacher">
    <property name="teacherId" value="10010"></property>
    <property name="teacherName" value="大寶"></property>
</bean>

<bean id="teacherTwo" class="org.example.bean.Teacher">
    <property name="teacherId" value="10086"></property>
    <property name="teacherName" value="二寶"></property>
</bean>

<bean id="studentFour" class="org.example.bean.Student">
    <property name="id" value="1004"></property>
    <property name="name" value="趙六"></property>
    <property name="age" value="26"></property>
    <property name="sex" value=""></property>
    <!-- ref屬性:引用IOC容器中某個(gè)bean的id,將所對(duì)應(yīng)的bean為屬性賦值 -->
    <property name="clazz" ref="clazzOne"></property>
    <property name="hobbies">
        <array>
            <value>抽煙</value>
            <value>喝酒</value>
            <value>燙頭</value>
        </array>
    </property>
    <property name="teacherMap">
        <map>
            <entry>
                <key>
                    <value>10010</value>
                </key>
                <ref bean="teacherOne"></ref>
            </entry>
            <entry>
                <key>
                    <value>10086</value>
                </key>
                <ref bean="teacherTwo"></ref>
            </entry>
        </map>
    </property>
</bean>
③引用集合類型的bean
<!--list集合類型的bean-->
<util:list id="students">
    <ref bean="studentOne"></ref>
    <ref bean="studentTwo"></ref>
    <ref bean="studentThree"></ref>
</util:list>
<!--map集合類型的bean-->
<util:map id="teacherMap">
    <entry>
        <key>
            <value>10010</value>
        </key>
        <ref bean="teacherOne"></ref>
    </entry>
    <entry>
        <key>
            <value>10086</value>
        </key>
        <ref bean="teacherTwo"></ref>
    </entry>
</util:map>
<bean id="clazzTwo" class="org.example.bean.Clazz">
    <property name="clazzId" value="4444"></property>
    <property name="clazzName" value="Javaee0222"></property>
    <property name="students" ref="students"></property>
</bean>
<bean id="studentFour" class="org.example.bean.Student">
    <property name="id" value="1004"></property>
    <property name="name" value="趙六"></property>
    <property name="age" value="26"></property>
    <property name="sex" value=""></property>
    <!-- ref屬性:引用IOC容器中某個(gè)bean的id,將所對(duì)應(yīng)的bean為屬性賦值 -->
    <property name="clazz" ref="clazzOne"></property>
    <property name="hobbies">
        <array>
            <value>抽煙</value>
            <value>喝酒</value>
            <value>燙頭</value>
        </array>
    </property>
    <property name="teacherMap" ref="teacherMap"></property>
</bean>

使用util:list、util:map標(biāo)簽必須引入相應(yīng)的命名空間文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-479212.html

<?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:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/util
       http://www.springframework.org/schema/util/spring-util.xsd
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

到了這里,關(guān)于Spring IOC基于XML和注解管理Bean(一)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來(lái)自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • Spring基于注解管理bean及全注解開(kāi)發(fā)

    Spring基于注解管理bean及全注解開(kāi)發(fā)

    Spring是一款主流的Java EE 輕量級(jí)開(kāi)源框架,目的是用于簡(jiǎn)化Java企業(yè)級(jí)引用的開(kāi)發(fā)難度和開(kāi)發(fā)周期。從簡(jiǎn)單性、可測(cè)試性和松耦合度的角度而言,任何Java應(yīng)用都可以從Spring中受益。Spring框架提供自己提供功能外,還提供整合其他技術(shù)和框架的能力。 Spring自誕生以來(lái)備受青睞,

    2024年02月14日
    瀏覽(64)
  • Spring-1-透徹理解Spring XML的Bean創(chuàng)建--IOC

    Spring-1-透徹理解Spring XML的Bean創(chuàng)建--IOC

    上一篇文章我們介紹了什么是Spring,以及Spring的一些核心概念,并且快速快發(fā)一個(gè)Spring項(xiàng)目,實(shí)現(xiàn)IOC和DI,今天具體來(lái)講解IOC 能夠說(shuō)出IOC的基礎(chǔ)配置和Bean作用域 了解Bean的生命周期 能夠說(shuō)出Bean的實(shí)例化方式 問(wèn)題導(dǎo)入 問(wèn)題1:在 bean 標(biāo)簽上如何配置別名? 問(wèn)題2:Bean的默認(rèn)作用

    2024年02月13日
    瀏覽(22)
  • 7、Spring之基于注解管理bean

    7、Spring之基于注解管理bean

    本質(zhì)上:所有一切的操作都是Java代碼來(lái)完成的,XML和注解只是告訴框架中的Java代碼如何執(zhí)行。 創(chuàng)建名為spring_ioc_annotation的新module,過(guò)程參考3.1節(jié) 注解 含義 @Component 將類標(biāo)識(shí)為普通組件 @Controller 將類標(biāo)識(shí)為控制層組件 @Service 將類標(biāo)識(shí)為業(yè)務(wù)層組件 @Repository 將類標(biāo)識(shí)為持久

    2024年02月14日
    瀏覽(19)
  • 11Spring IoC注解式開(kāi)發(fā)(上)(元注解/聲明Bean的注解/注解的使用/負(fù)責(zé)實(shí)例化Bean的注解)

    11Spring IoC注解式開(kāi)發(fā)(上)(元注解/聲明Bean的注解/注解的使用/負(fù)責(zé)實(shí)例化Bean的注解)

    注解的存在主要是為了簡(jiǎn)化XML的配置。Spring6倡導(dǎo)全注解開(kāi)發(fā)。 注解開(kāi)發(fā)的優(yōu)點(diǎn) :提高開(kāi)發(fā)效率 注解開(kāi)發(fā)的缺點(diǎn) :在一定程度上違背了OCP原則,使用注解的開(kāi)發(fā)的前提是需求比較固定,變動(dòng)較小。 自定義一個(gè)注解: 該注解上面修飾的注解包括:Target注解和Retention注解,這兩個(gè)注

    2024年01月21日
    瀏覽(30)
  • 【Spring進(jìn)階系列丨第六篇】Spring的Bean管理(基于注解)

    【Spring進(jìn)階系列丨第六篇】Spring的Bean管理(基于注解)

    回顧一下 基于xml配置的Spring對(duì)Bean的管理 ,對(duì)Bean的完整管理如下所示: 分析可以發(fā)現(xiàn):我們對(duì)Bean的管理就四個(gè)方面,分別是: 用于創(chuàng)建對(duì)象的 用于注入數(shù)據(jù)的 用于改變Bean的作用域的 和Bean的生命周期相關(guān)的 其實(shí)對(duì)于注解來(lái)說(shuō),也是包括了這四個(gè)方面,換句話說(shuō), 使用注

    2024年02月03日
    瀏覽(26)
  • 【Spring進(jìn)階系列丨第四篇】學(xué)習(xí)Spring中的Bean管理(基于xml配置)

    【Spring進(jìn)階系列丨第四篇】學(xué)習(xí)Spring中的Bean管理(基于xml配置)

    在之前的學(xué)習(xí)中我們知道,容器是一個(gè)空間的概念,一般理解為可盛放物體的地方。在Spring容器通常理解為BeanFactory或者ApplicationContext。我們知道spring的IOC容器能夠幫我們創(chuàng)建對(duì)象,對(duì)象交給spring管理之后我們就不用手動(dòng)去new對(duì)象。 那么Spring是如何管理Bean的呢? 簡(jiǎn)而言之,

    2024年02月05日
    瀏覽(24)
  • Spring注解驅(qū)動(dòng)開(kāi)發(fā)之常用注解案例_告別在XML中配置Bean

    注解驅(qū)動(dòng)開(kāi)發(fā)就是不再使用Spring的bean.xml文件,改為純使用注解的方式開(kāi)發(fā) @Configuration 此注解為配置類注解,相當(dāng)于spring.xml文件,即配置類==配置文件 @Bean 給容器中注冊(cè)一個(gè)Bean;類型為返回值的類型,id默認(rèn)是用方法名作為id 示例 Person類(后續(xù)注解配置類中都會(huì)以此類舉例),

    2024年01月21日
    瀏覽(28)
  • 【Spring篇】IOC/DI配置管理第三方bean

    【Spring篇】IOC/DI配置管理第三方bean

    ??系列專欄:Spring系列專欄 ??個(gè)人主頁(yè):個(gè)人主頁(yè) 目錄 一、案例:數(shù)據(jù)源對(duì)象管理 1.環(huán)境準(zhǔn)備 2.實(shí)現(xiàn)Druid管理 3.實(shí)現(xiàn)C3P0管理 二、加載properties文件 1.第三方bean屬性優(yōu)化 2.讀取單個(gè)屬性 3.注意事項(xiàng) ? 三、核心容器 1.環(huán)境準(zhǔn)備 2.容器 ? 1.容器的創(chuàng)建方式 2.Bean的三種獲取方式 3.容器

    2024年02月02日
    瀏覽(25)
  • Spring使用注解管理Bean

    Spring使用注解管理Bean

    引入lib包 Spring對(duì)Bean管理的常用注解 @Component組件(作用在類上) Spring中提供了@Component的三個(gè)衍生注解:(功能在目前為止是一致的) @Controller WEB層 @Service 業(yè)務(wù)層 @Repository 持久層 屬性注入的注解:(使用注解注入的方式,可以不用提供set方法) @Value? 用于注入普通類型 @Autowired? 自動(dòng)裝

    2024年01月17日
    瀏覽(30)
  • 從入門到精通:掌握Spring IOC/DI配置管理第三方bean的技巧

    從入門到精通:掌握Spring IOC/DI配置管理第三方bean的技巧

    以后我們會(huì)用到很多第三方的bean,我們以數(shù)據(jù)源是 Druid(德魯伊) 和 C3P0 來(lái)配置舉個(gè)例子。 1.1.1 環(huán)境準(zhǔn)備 先來(lái)準(zhǔn)備下案例環(huán)境: 1.1.2 思路分析 需求:使用Spring的IOC容器來(lái)管理Druid連接池對(duì)象 1.使用第三方的技術(shù),需要在pom.xml添加依賴 2.在配置文件中將【第三方的類】制作成一個(gè)

    2024年02月02日
    瀏覽(24)

覺(jué)得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包