雷火电竞-中国电竞赛事及体育赛事平台

歡迎來到入門教程網(wǎng)!

Java

當前位置:主頁 > 軟件編程 > Java >

Spring基于xml文件配置Bean過程詳解

來源:本站原創(chuàng)|時間:2020-01-10|欄目:Java|點擊:

這篇文章主要介紹了spring基于xml文件配置Bean過程詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下

通過全類名來配置:

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的實例之前,需要對容器進行實例化。spring提供了兩種類型的IOC容器實現(xiàn):

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

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

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

  • ClassPathXmlApplicationContext:從類路徑加載配置文件。
  • FileSystemXmlApplicationContext:從文件系統(tǒng)中加載配置文件。
  • ConfigureableApplicationContext擴展于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ù)進行一一設(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());
  }

輸出:

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

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

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

上一篇:Java實現(xiàn)按比抽獎功能

欄    目:Java

下一篇:springboot全局異常處理代碼實例

本文標題:Spring基于xml文件配置Bean過程詳解

本文地址:http://www.jygsgssxh.com/a1/Java/8724.html

網(wǎng)頁制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語言數(shù)據(jù)庫服務(wù)器

如果侵犯了您的權(quán)利,請與我們聯(lián)系,我們將在24小時內(nèi)進行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有