Spring控制反转+依赖注入

2014-11-24 02:08:42 · 作者: · 浏览: 0

减少开发工作量,减少组件之间的耦合

spring框架是一个开源的轻量级的基于IOC与AOP核心技术的容器框架,主要是解决企业的复杂操作实现。

那IOC与AOP,到底如何解释呢,

IOC:inverse of Control:控制反转。意思是程序中的之间的关系,不用代码控制,而完全是由容器来控制。

在运行阶段,容器会根据配置信息直接把他们的关系注入到组件中。

这也是依赖注入的含义。依赖注入和控制反转其实是一个概念。

只不过强调的不同而已,依赖注入强调关系的注入是由容器在运行时完成,而控制反转强调关系是由容器控制。其实本质是一样的。

用代码演示一下控制反转是如何实现的。

  1. public class School {
  2. private String name;
  3. public School(String name)
  4. {
  5. this.name=name;
  6. }
  7. public void printInfo()
  8. {
  9. System.out.println("该学校的名称是:"+name);
  10. }
  11. }

    1. public int id;
    2. public String name;
    3. private School school;
    4. public int getId() {
    5. return id;
    6. }
    7. public void setId(int id) {
    8. this.id = id;
    9. }
    10. public String getName() {
    11. return name;
    12. }
    13. public void setName(String name) {
    14. this.name = name;
    15. }
    16. public School getSchool() {
    17. return school;
    18. }
    19. public void setSchool(School school) {
    20. this.school = school;
    21. }
    22. }

      配置文件:


      1. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      2. xmlns:aop="http://www.springframework.org/schema/aop"
      3. xmlns:tx="http://www.springframework.org/schema/tx"
      4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
      5. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
      6. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
      7. 廊坊师院


      8. 客户端进行测试,其中学生类Student中有School中的引用,测试该学生就读的学校的名称如下:


        copy
        1. package ioc.iocsample;
        2. import org.springframework.beans.factory.BeanFactory;
        3. import org.springframework.context.support.ClassPathXmlApplicationContext;
        4. public class Client {
        5. public static void main(String[] args) {
        6. // TODO Auto-generated method stub
        7. BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
        8. Student student=(Student)factory.getBean("student");
        9. student.getSchool().printInfo();
        10. }
        11. }


          其中依赖注入包括两种:一种赋值注入(使用getter和setter方法);另一种使用构造器注入。

          看程序中student中的ID,name都是使用get,set来赋值的:那在配置文件是如下配置:


          并且Student中的school属性是School类型,则在容器中是如下配置的:

          而在程序中的School中的name是构造器赋值的,则容器中是如下配置的:


          廊坊师院

          构造器中一个参数,则索引值是从0开始,若是有多个,依次递增。

          若构造器中的是一个类,则使用bean标签


          三种注入方式的区别:

          1.接口注入:组件需要依赖特定接口的实现,其中的加载接口实现和接口实现的具体对象都是由容器来完成。这样,接口必须依赖容器,这样的组件具有侵入性,降低了重用性。其中如J2EE开发中常用的Context.lookup(ServletContext.getXXX),都是接口注入的表现形式。(这种注入方式不是常用的)

          2.getter/setter方式注入:对于需要注入的东西比较明确。符合java的设计规则。更适合java开发人员,使用起来更加自然,更加方便。

          3.构造器方式注入:在类加载的时候,就已经注入依赖的组件。但是若是参数多的话,使用起来不方便。

          但是后两种注入方式是spring常用的,而第一种接口注入方式不常用。