這篇文章主要介紹了spring基于xml文件配置Bean過程詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
通過全類名來配置:
class:bean的全類名,通過反射的方式在IOC容器中創建Bean,所以要求bean中必須有一個無參的構造器。
在springIOC容器讀取Bean配置創建Bean的實例之前,需要對容器進行實例化。spring提供了兩種類型的IOC容器實現:
beanfactory:IOC容器的基本實現。
ApplicationContext:提供了更多高級特性,是beanfactory的子接口。
ApplicationContext主要實現類:
ClassPathXmlApplicationContext:從類路徑加載配置文件。
FileSystemXmlApplicationContext:從文件系統中加載配置文件。
ConfigureableApplicationContext擴展于ApplicationContext,新增兩個方法refresh()和close(),讓ApplicationContext具有啟動、刷新和關閉上下文的能力。
ApplicaiotnContex在初始化時就上下文時就實例化所有單例的Bean。
WebApplicationContext是專門用于WEB應用的,它允許從相對于WEB根目錄的路徑中完成初始化工作。
依賴注入的三種方式
(1)屬性注入:通過setter方法:,即在bean中存在setter方法。
(2)構造器注入:,根據構造方法中初始化的參數進行一一設置,同時,可以根據參數的順序index,參數的類型type來區分重載的構造器。
(3)工廠方法注入(很少使用,不推薦)
//第一種方式注入屬性值
//第二種方式注入屬性值
99.00
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.創建spring的IOC容器對象
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
//2.從容器中獲取Bean實例
Student student = (Student) ctx.getBean("student");
System.out.println(student.toString());
}
當屬性值有特殊符號時,要用以下方式:
]]>
用。
相關文章
總結
如果覺得編程之家網站內容還不錯,歡迎將編程之家網站推薦給程序員好友。
本圖文內容來源于網友網絡收集整理提供,作為學習參考使用,版權屬于原作者。
如您喜歡交流學習經驗,點擊鏈接加入交流1群:1065694478(已滿)交流2群:163560250