溫馨提示×

溫馨提示×

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

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

怎么在Spring中利用xml文件配置Bean

發(fā)布時間:2021-05-25 16:36:26 來源:億速云 閱讀:175 作者:Leah 欄目:編程語言

這篇文章將為大家詳細(xì)講解有關(guān)怎么在Spring中利用xml文件配置Bean,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。

通過全類名來配置:

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

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

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

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

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

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

  • ClassPathXmlApplicationContext:從類路徑加載配置文件。

  • FileSystemXmlApplicationContext:從文件系統(tǒng)中加載配置文件。

  • ConfigureableApplicationContext擴(kuò)展于ApplicationContext,新增兩個方法refresh()和close(),讓ApplicationContext具有啟動、刷新和關(guān)閉上下文的能力。

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

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

依賴注入的三種方式

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

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

(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());
  }

輸出:

怎么在Spring中利用xml文件配置Bean

當(dāng)屬性值有特殊符號時,要用以下方式:

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

關(guān)于怎么在Spring中利用xml文件配置Bean就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

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

AI