码迷,mamicode.com
首页 > 编程语言 > 详细

简单的Spring Ioc

时间:2015-06-26 10:56:25      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

  控制反转(Inversion of Control,Ioc),也被称为依赖注入(Dependency Injection,DI),是面向对象的一种设计理念,用来降低程序代码之间的耦合度。

  首先要考虑什么是依赖。依赖,在代码中一般是指通过局部变量、方法参数、返回值等建立的对于其他对象的调用关系。例如,A类的方法中,实例化了B类的对象并调用其方法已完成特定的功能,我们就说A类依赖于B类

  

  ---------------------------正文---------------------------

  我们需要这spring 框架的jar包

  

  org.springframework.asm-3.1.1.RELEASE.jar
  org.springframework.beans-3.1.1.RELEASE.jar
  org.springframework.context.support-3.1.1.RELEASE.jar
  org.springframework.context-3.1.1.RELEASE.jar
  org.springframework.core-3.1.1.RELEASE.jar
  org.springframework.expression-3.1.1.RELEASE.jar

  我们可以去http://www.springsource.org下载

 

  第一步

  新建项目把需要的jar包导入进去

  

  第二步

  创建HelloSpring实体类

public class HelloSpring {
    //定义who属性,该属性的值将通过Spring框架进行设置
    private String who = null;
    
    /**
     * 定义打印方法,输出一句完整的问候
     */
    public void print(){
        System.out.println("Hello,"+this.getWho() + "!");
    }

    
    public String getWho() {
        return who;
    }

    public void setWho(String who) {
        this.who = who;
    }
    
    
}

  

  第三步

  

  创建applicationContext.xml

  

  

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:aop="http://www.springframework.org/schema/aop"
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans
 6     http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
 7     http://www.springframework.org/schema/aop
 8     http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
 9     <!-- 通过bean元素声明需要Spring创建的实例。该实例的类型通过class属性指定, -->
10     <!-- 并通过id属性为该实例指定一个名称,以便在程序中使用 -->
11     <bean id="helloSpring" class="entity.HelloSpring">
12         <!-- property元素用来为实例的属性赋值,此处实际是调用setWho()方法实现赋值操作 -->
13         <property name="who">
14             
15             <value>Spring</value>
16         </property>
17     </bean>    
18 </beans>

  

  第四步

  

  编写测试类

  

  

 1 package text;
 2 
 3 import org.springframework.context.ApplicationContext;
 4 import org.springframework.context.support.ClassPathXmlApplicationContext;
 5 
 6 import entity.HelloSpring;
 7 
 8 public class TextSpring {
 9     public static void main(String[] args) {
10         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
11         //helloSpring对应applicationContext bean的id属性
12         HelloSpring helloSpring = (HelloSpring) context.getBean("helloSpring");
13         helloSpring.print();
14     }
15 }

这样一个简单的Spring Ioc就做好了


 

 

 

  

  

  

简单的Spring Ioc

标签:

原文地址:http://www.cnblogs.com/lanziyao/p/4601647.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!