zoukankan      html  css  js  c++  java
  • SSH深度历险记(八) 剖析SSH核心原则+Spring依赖注入的三种方式

           于java发育。一类程序猿必须依靠类的其他方法,它是通常new依赖类的方法,然后调用类的实例,这样的发展问题new良好的班统一管理的例子。spring提出了依赖注入的思想,即依赖类不由程序猿实例化,而是通过spring容器帮我们new指定实例而且将实例注入到须要该对象的类中。依赖注入的还有一种说法是“控制反转”,通俗的理解是:寻常我们new一个实例,这个实例的控制权是我们程序猿,而控制反转是指new实例工作不由我们程序猿来做而是交给spring容器来做。

    Spring依赖注入(DI)的三种方式,分别为:

    1.  Setter方法注入

    2.  构造方法注入

    3.  接口注入


    以下介绍一下这三种依赖注入在Spring中是怎么样实现的。

     Setter方法注入

    首先我们须要下面几个类:

    接口 Logic.java

    接口实现类 LogicImpl.java

    一个处理类 LoginAction.java

    另一个測试类 TestMain.java

    Logic.java例如以下:


    <span style="font-size:18px;"><span style="font-size:18px;">package DI;
    //定义接口
    public interface Logic {
    	public String getName();
    }
    </span></span>

    LogicImpl.java例如以下:
    <span style="font-size:18px;"><span style="font-size:18px;">package DI;
    
    public class LogicImpl implements Logic {
    //实现类
    
    	public String getName() {
    		
    		return "lishehe";
    	}
    
    }
    </span></span>

    LoginAction.java 会依据使用不同的注入方法而稍有不同

    Setter方法注入:

    <span style="font-size:18px;"><span style="font-size:18px;">package DI;
    
    public class LoginAction {
    	 private Logic logic;
    
    	 
    
    	    public void execute() {
    
    	       String name = logic.getName();
    
    	       System.out.print("My Name Is " + name);  
    
    	    }
    
    	 
    
    	    /**
    
    	     * @return the logic
    
    	     */
    
    	    public Logic getLogic() {
    
    	       return logic;
    
    	    }
    
    	 
    
    	    /**
    
    	     * @param logic
    
    	     *            the logic to set
    
    	     */
    
    	    public void setLogic(Logic logic) {
    
    	       this.logic = logic;
    
    	    }
    }
    </span></span>


    client測试类

    TestMain.java

    <span style="font-size:18px;">package DI;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.FileSystemXmlApplicationContext;
    
    public class TestMain {
    
    	 /**
    
         * @param args
    
         */
    
        public static void main(String[] args) {
    
     
    
           // 得到ApplicationContext对象
    
           ApplicationContext ctx = new FileSystemXmlApplicationContext(
    
                  "applicationContext.xml");
    
           // 得到Bean
    
           LoginAction loginAction = (LoginAction) ctx.getBean("loginAction");
    
          
    
           loginAction.execute();
    
        }
    }
    </span>

    定义了一个Logic 类型的变量 logic, LoginAction并没有对logic 进行实例化,而仅仅有他相应的setter/getter方法。由于我们这里使用的是Spring的依赖注入的方式

     

    applicationContext.xml配置文件例如以下:

    <span style="font-size:18px;"><?xml version="1.0" encoding="UTF-8"?>
    
    <!--
      - Application context definition for JPetStore's business layer.
      - Contains bean references to the transaction manager and to the DAOs in
      - dataAccessContext-local/jta.xml (see web.xml's "contextConfigLocation").
      -->
    <beans xmlns="http://www.springframework.org/schema/beans"
    		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    		xmlns:aop="http://www.springframework.org/schema/aop"
    		xmlns:tx="http://www.springframework.org/schema/tx"
    		xsi:schemaLocation="
    			http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    			http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
    			http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
    	
    
    <bean id="logic" class="DI.LogicImpl"/>
    
    <bean id="loginAction" class="DI.LoginAction">
    
     <property name="logic" ref="logic"></property>
    
    </bean>
    
    </beans>
    </span>

    执行效果:



    构造器注入

    顾名思义。构造方法注入,就是我们依靠LoginAction的构造方法来达到DI的目的。例如以下所看到的:

    <span style="font-size:18px;">package DI;
    
    public class LoginAction {
    	
    	
    	 private Logic logic;
    
    	 
    
    	    public LoginAction(Logic logic) {
    
    	       this.logic = logic;
    
    	    }
    
    	 
    
    	    public void execute() {
    
    	       String name = logic.getName();
    
    	       System.out.print("My Name Is " + name);
    
    	    }
    	
    }
    </span>

    里我们加入了一个LoginAction的构造方法

    applicationContext.xml配置文件例如以下:

    <span style="font-size:18px;">	<bean id="logic" class="DI.LogicImpl"/>
    
    <bean id="loginAction" class="DI.LoginAction">
    
     <constructor-arg index="0" ref="logic"></constructor-arg>
    
    </bean></span>

    我们使用constructor-arg来进行配置, index属性是用来表示构造方法中參数的顺序的,假设有多个參数,则依照顺序。从 0,1...来配置

     

    我们如今能够执行testMain.java,结果跟使用Setter方法注入全然一样.

     效果图


     

    当中须要注意一点有:构造函数有多个參数的话,如:參数1,參数2,而參数2依赖于參数1,这中情况则要注意构造函数的顺序,必须将參数1放在參数2之前。

    接口注入

    以下继续说说我们不经常使用到的接口注入,还是以LogicAction为例,我们对他进行了改动,例如以下所看到的:

    LogicAction.java

    <span style="font-size:18px;">package DI;
    
    public class LoginAction {
    	
    	private Logic logic;
    
    	 
    
        public void execute() {
    
           try {
    
               Object obj = Class.forName("DI.LogicImpl")
    
                      .newInstance();
    
               logic = (Logic) obj;
    
               String name = logic.getName();
    
               System.out.print("My Name Is " + name);
    
           } catch (Exception e) {
    
               e.printStackTrace();
    
           }
    
        }
    	
    	 
    
    }
    </span>

    配置文件:

    <span style="font-size:18px;"><bean id="logic" class="DI.LogicImpl"/>
    
    <bean id="loginAction" class="DI.LoginAction"></span>
    效果图




    总结

        对于Spring的依赖注入。最重要的就是理解他的,一旦理解了,将会认为很的简单。无非就是让容器来给我们实例化那些类。我们要做的就是给容器提供这个接口。这个接口就我们的set方法或由构造。


    版权声明:本文博主原创文章,博客,未经同意不得转载。

  • 相关阅读:
    Hibernate事务代码规范写法
    关于hibernate插入数据时的乱码问题
    搭建hibernate环境(重点)
    接口测试概念以及用postman进行接口测试
    Atom编辑器之加快React开发的插件汇总
    如何搭建git服务器
    phpstorm 配置 xdebug调试工具
    linux 获取指定行范围文本内容
    odoo 创建一个qweb
    linux nohup 使用
  • 原文地址:https://www.cnblogs.com/lcchuguo/p/4819564.html
Copyright © 2011-2022 走看看