溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Spring基于xml文件配置Bean過程是怎樣的

發(fā)布時間:2021-10-13 11:21:07 來源:億速云 閱讀:123 作者:柒染 欄目:編程語言

Spring基于xml文件配置Bean過程是怎樣的,相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。

通過全類名來配置:

class:bean的全類名,通過反射的方式在IOC容器中創(chuàng)建Bean,所以要求bean中必須有一個無參的構造器。

<bean id="helloWorld" class="com.gong.spring.beans.HelloWorld">    <property name="name" value="jack"></property>  </bean>

在springIOC容器讀取Bean配置創(chuàng)建Bean的實例之前,需要對容器進行實例化。spring提供了兩種類型的IOC容器實現(xiàn):

Beanfactory:IOC容器的基本實現(xiàn)。

ApplicationContext:提供了更多高級特性,是BeanFactory的子接口。

ApplicationContext主要實現(xiàn)類:

ClassPathXmlApplicationContext:從類路徑加載配置文件。FileSystemXmlApplicationContext:從文件系統(tǒng)中加載配置文件。ConfigureableApplicationContext擴展于ApplicationContext,新增兩個方法refresh()和close(),讓ApplicationContext具有啟動、刷新和關閉上下文的能力。

ApplicaiotnContex在初始化時就上下文時就實例化所有單例的Bean。

WebApplicationContext是專門用于WEB應用的,它允許從相對于WEB根目錄的路徑中完成初始化工作。

依賴注入的三種方式

(1)屬性注入:通過setter方法:<property name="name" value="jack"></property>,即在bean中存在setter方法。

(2)構造器注入:<constructor-arg value="" index="0" type=""></constructor-arg>,根據(jù)構造方法中初始化的參數(shù)進行一一設置,同時,可以根據(jù)參數(shù)的順序index,參數(shù)的類型type來區(qū)分重載的構造器。

(3)工廠方法注入(很少使用,不推薦)

<bean id="student" class="com.gong.spring.beans.Student">    //第一種方式注入屬性值    <constructor-arg value="tom" index="0" type="java.lang.String"></constructor-arg>    <constructor-arg value="12" index="1" type="int"></constructor-arg>    //第二種方式注入屬性值    <constructor-arg index="2" type="double">      <value>99.00</value>    </constructor-arg>  </bean>

package com.gong.spring.beans;public class Student {  private String name;  private int age;  private double score;  public Student(String name,int age,double score) {    this.name = name;    this.age = age;    this.score = score;  }  @Override  public String toString() {    return "Student [name=" + name + ", age=" + age + ", score=" + score + "]";  }}

public static void main(String[] args) {    //1.創(chuàng)建spring的IOC容器對象    ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");    //2.從容器中獲取Bean實例    Student student = (Student) ctx.getBean("student");    System.out.println(student.toString());  }

輸出:

當屬性值有特殊符號時,要用以下方式:

<constructor-arg index="0" type="java.lang.String">      <value><![CDATA[<tom>]]></value>    </constructor-arg>

用<![CDATA[屬性值]]>。

看完上述內(nèi)容,你們掌握Spring基于xml文件配置Bean過程是怎樣的的方法了嗎?如果還想學到更多技能或想了解更多相關內(nèi)容,歡迎關注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI