Spring 基於XML配置的IOC入門案例


所謂Ioc(Inverse Of Control),就是通過容器來控制業務對象之間的依賴關係,而非傳統的由代碼直接控制,即控制權由應用代碼中轉到了外部容器,控制權發生了轉移。控制權的轉移帶來的好處就是降低了業務對象之間的依賴程序--鬆耦合。

下面以一個簡單的例子具體闡述

1、新建一個Java Project 目錄結構如下:

 

Car類源碼:
package com;
public class Car {
 
 private String brand;
 private String color;
 private int maxSpeed;
 
 public String getBrand() {
  return brand;
 }
 public void setBrand(String brand) {
  this.brand = brand;
 }
 public String getColor() {
  return color;
 }
 public void setColor(String color) {
  this.color = color;
 }
 public int getMaxSpeed() {
  return maxSpeed;
 }
 public void setMaxSpeed(int maxSpeed) {
  this.maxSpeed = maxSpeed;
 }
 
 public String toString(){
  return "Car:brand-"+brand+" color-"+color+" maxSpeed-"+maxSpeed;
 }
}
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-3.2.xsd">
    <bean id="car" class="com.Car">
        <property name="brand" value="紅旗CA72"/>
        <property name="color" value="黑色"/>
        <property name="maxSpeed" value="200"/>
    </bean>
</beans>
 
Test類源碼:
package com;

import java.io.File;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

public class Test {

	public static void main(String[] args) {
		String path=new File("").getAbsolutePath()+"/src/com/beans.xml";
		Resource res=new FileSystemResource(path);
		BeanFactory factory=new XmlBeanFactory(res);
		Car car=(Car) factory.getBean("car");
		System.out.println(car);
	}

}
 
運行Test,輸出結果:Car:brand-紅旗CA72 color-黑色 maxSpeed-200
 
1、通過new FileSystemResource(path)來定位Spring配置文件並生成Resource對象;
2、通過new XmlBeanFactory(res)來裝載Spring配置信息,並啓動IoC容器;
3、通過BeanFactory#getBean(beanName)(此時開始實例化對象並裝載)從Ioc容器中獲取Bean。
發佈了24 篇原創文章 · 獲贊 4 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章