`
yunmanfan
  • 浏览: 91064 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Spring中的IoC(控制反转)容器初探

阅读更多
IoC,翻译成中文有人叫控制反转,听起来很别别扭,其实就是依赖关系的转移,通过XML配置文件由容器来管理类,而不是在类中直接生成Bean的实例。

下面通过一个Hello World的实例来了解一下最基础的IoC

首先MyEclipse5.5新建一个Java工程,工程名上单击右键添加Spring容器能力。

我们先编写一个HelloWorld类

qiudawei115.base.HelloWorld.java

package qiudawei115.base;



public class HelloWorld {

    String message;



    public String getMessage() {

       return message;

    }



    public void setMessage(String message) {

       this.message = message;

    }

}

注意这只是一个简单的Bean,没有任何其他东西。

在applicationContext.xml配置qiudawei115.base.HelloWorld(红色字体)

<?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-2.0.xsd">

<bean id="helloWorld" class="qiudawei115.base.HelloWorld">

    <property name="message" value="Hello World!"></property>

</bean>

</beans>

现在写一个测试类,检验一下qiudawei115.base.HelloWorldMain.java

package qiudawei115.base;



import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.core.io.ClassPathResource;

public class HelloWorldMain {



    /**

     * @param args

     */

    public static void main(String[] args) {

       // TODO Auto-generated method stub

//读取配置文件 

ClassPathResource resource=new ClassPathResource("applicationContext.xml");

       BeanFactory beanFactory=new XmlBeanFactory(resource);

//获取HelloWorld实例     

HelloWorld helloWorld=(HelloWorld)beanFactory.getBean("helloWorld");

       System.out.print(helloWorld.getMessage());

    }

}

这样就完成了一个简单的IoC实例。

这里我们的Bean是由xml文件去管理的,我们索要做的就是从xml中获取这个类的实例。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics