依赖注入的方式

前端之家收集整理的这篇文章主要介绍了依赖注入的方式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
依赖注入的基本原则是:应用组件不应该负责查找资源或者其他依赖的协作对象。配置对象的工作应该由IoC容器负责,“查找资源”的逻辑应该从应用组件的代码中抽取出来,交给IoC容器负责。
下面分别演示3中注入机制。
代码 2 待注入的业务对象 Content.java
package com.zj.ioc.di;
public class Content {
void BusniessContent(){
System. out .println( "do business" );
}
void AnotherBusniessContent(){
System. "do another business" );
}
}
MyBusniess类展示了一个业务组件,它的实现需要对象Content的注入。代码3,代码4,代码5,6分别演示构造子注入(Constructor Injection),设值注入(Setter Injection)和接口注入(Interface Injection)三种方式。
代码 3构造子注入(Constructor Injection) MyBusiness.java
packagecom.zj.ioc.di.ctor;
import com.zj.ioc.di.Content;
class MyBusiness {
private Content myContent ;
public MyBusiness(Content content) {
myContent = content;
}
void doBusiness(){
myContent .BusniessContent();
}
void doAnotherBusiness(){
myContent .AnotherBusniessContent();
}
}
代码 4设值注入(Setter Injection) MyBusiness.java
packagecom.zj.ioc.di.set;
void setContent(Content content) {
myContent .AnotherBusniessContent();
}
}
代码 5 设置注入接口 InContent.java
packagecom.zj.ioc.di.iface;
interface InContent {
void createContent(Content content);
}
代码 6接口注入(Interface Injection) MyBusiness.java
classMyBusinessimplementsInContent{
void createContent(Content content) {
void doBusniess(){
void doAnotherBusniess(){
5.依赖拖拽(Dependency Pull)
最后需要介绍的是依赖拖拽,注入的对象如何与组件发生联系,这个过程就是通过依赖拖拽实现。
代码7依赖拖拽示例
public static void main(String[] args) throws Exception{
//get the bean factory
beanfactory factory = getbeanfactory();
MessageRender mr = (MessageRender) factory.getBean(“renderer”);
mr.render();
}
而通常对注入对象的配置可以通过一个xml文件完成。
使用这种方式对对象进行集中管理,使用依赖拖拽与依赖查找本质的区别是,依赖查找是在业务组件代码中进行的,而不是从一个集中的注册处,特定的地点执行。

================================================================================================================
在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如下: @H_892_502@


  1. <spanstyle="font-size:18px;"><spanstyle="font-size:18px;">packageDI;
  2. //定义接口
  3. publicinterfaceLogic{
  4. publicStringgetName();
  5. }
  6. </span></span>

LogicImpl.java如下:
@H_403_578@
  1. publicclassLogicImplimplementsLogic{
  2. //实现类
  3. publicStringgetName(){
  4. return"lishehe";
  5. </span></span>

@H_892_502@

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

Setter方法注入:

@H_403_578@
    publicclassLoginAction{
  1. privateLogiclogic;
  2. publicvoidexecute(){
  3. Stringname=logic.getName();
  4. System.out.print("MyNameIs"+name);
  5. }
  6. /**
  7. *@returnthelogic
  8. */
  9. publicLogicgetLogic(){
  10. returnlogic;
  11. *@paramlogic
  12. *thelogictoset
  13. publicvoidsetLogic(Logiclogic){
  14. this.logic=logic;
  15. </span></span>


@H_892_502@

客户端测试类

TestMain.java

@H_403_578@
    <spanstyle="font-size:18px;">packageDI;
  1. importorg.springframework.context.ApplicationContext;
  2. importorg.springframework.context.support.FileSystemXmlApplicationContext;
  3. publicclassTestMain{
  4. *@paramargs
  5. publicstaticvoidmain(String[]args){
  6. //得到ApplicationContext对象
  7. ApplicationContextctx=newFileSystemXmlApplicationContext(
  8. "applicationContext.xml");
  9. //得到Bean
  10. LoginActionloginAction=(LoginAction)ctx.getBean("loginAction");
  11. loginAction.execute();
  12. </span>

@H_892_502@

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

applicationContext.xml配置文件如下:

[html]
    <spanstyle="font-size:18px;"><?xmlversion="1.0"encoding="UTF-8"?>
  1. <!--
  2. -ApplicationcontextdefinitionforJPetStore'sbusinesslayer.
  3. -ContainsbeanreferencestothetransactionmanagerandtotheDAOsin
  4. -dataAccessContext-local/jta.xml(seeweb.xml's"contextConfigLocation").
  5. -->
  6. <beansxmlns="http://www.springframework.org/schema/beans"
  7. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  8. xmlns:aop="http://www.springframework.org/schema/aop"
  9. xmlns:tx="http://www.springframework.org/schema/tx"
  10. xsi:schemaLocation="
  11. http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  12. http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-2.5.xsd
  13. http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
  14. <beanid="logic"class="DI.LogicImpl"/>
  15. <beanid="loginAction"class="DI.LoginAction">
  16. <propertyname="logic"ref="logic"></property>
  17. </bean>
  18. </beans>
  19. </span>

@H_892_502@

运行效果:



构造器注入

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

@H_403_578@
    publicLoginAction(Logiclogic){
  1. </span>

@H_892_502@

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

applicationContext.xml配置文件如下:

    <spanstyle="font-size:18px;"><beanid="logic"class="DI.LogicImpl"/>
  1. <beanid="loginAction"class="DI.LoginAction">
  2. <constructor-argindex="0"ref="logic"></constructor-arg>
  3. </bean></span>

@H_892_502@

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

我们现在可以运行testMain.java,结果跟使用Setter方法注入完全一样.

效果


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

接口注入

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

LogicAction.java

@H_403_578@
    privateLogiclogic;
  1. publicvoidexecute(){
  2. try{
  3. Objectobj=Class.forName("DI.LogicImpl")
  4. .newInstance();
  5. logic=(Logic)obj;
  6. Stringname=logic.getName();
  7. System.out.print("MyNameIs"+name);
  8. }catch(Exceptione){
  9. e.printStackTrace();
  10. </span>

配置文件
@H_892_502@

    <spanstyle="font-size:18px;"><beanid="logic"class="DI.LogicImpl"/>
  1. <beanid="loginAction"class="DI.LoginAction"></span>
效果 @H_892_502@




总结

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

原文链接:https://www.f2er.com/javaschema/285103.html

猜你在找的设计模式相关文章