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。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值