一:这里先说一下DI(Dependency Injection)依赖注入有种表现形式:一种是CI(Constructor Injection)构造方法注入,另一种是SI(Set Injection) set 注入。这篇随笔讲的是第一种构造方法注入(Constructor Injection).

其实DI(Dependency Injection)依赖注入你不妨反过来读:注入依赖也就是把"依赖"注入到一个对象中去。那么何为"依赖"呢?依赖就是讲一个对象初始化或者将实例化的时候需要另一个对象,我们把另一个对象成为"依赖"。如构造方法注入(Constructor Injection)就是把依赖当做构造方法的参数注入进去的。如:

//Injection B to A. 我们把B称为依赖。一般情况下B是一个接口,这符合面向接口编程的规范。

public A (B b){

}

二:使用依赖注入的好处是什么?

  1.DI(Dependency Injection)最大的好处是decoupling(解耦)。如上面的代码把B注入给A如果B是一个接口或者抽象类。只要任何一个类实现或者继承B都可以注入给A.因此可以达到解耦的目的。

  2. 依赖注入给谁?        

dependencies injected into the objects that need them.(依赖注入给那些需要他们的对象。)

3.在spring中怎么让依赖传入到被依赖的对象(看上面的代码:怎么把B传入到A中)?

 在这里我引用一下spring in action中的一段文字:(注:我下面的示例代码基本跟spring in action 的一样)

The big question here is,how can you give SlayDragonQuest to BraveKnight ? And how can you give a PrintStream to SlayDragonQuest?

The act of creating associations between application components is commonly referred to as wiring.

spring通过配置配置文件,配置bean的形式,完成装配,又装配实现把依赖注入给需要他们的对象中的。

【我这里还想说明一下配置文件中的一个bean其实就对应一个javabean,也就是一个pojo对象,bean就是javabean的缩写形式而已】

示例代码的目录结构如下图所示:

  上面中的带两个圈的配置文件想说明两个问题:

一个是:new ClassPathXmlApplicationContext("spring-julysecond.xml");//注意这个.xml文件是在src目录下。

    new ClassPathXmlApplicationContext("com/config/spring-julythird.xml")//注意这个.xml文件在com.cofig这个文件下。

另一个问题是DI的解耦问题:spring-julysecond.xml文件中注入的是SlayDragonQuest,spring-julythird.xml注入的是SearchHillQuest.在不改变代码的情况下看传入的Quest的实现类不同,从而打出的结果不同。

spring-julysecond.xml的代码如下:

 <?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.xsd">
<!--this is constructor injection-->
<!--the act of creating associations between application components is commonly referred to
as wiring-->
<bean id="knight" class="com.qls.impl.BraveKnight">
<!-- collaborators and configuration for this bean go here -->
<constructor-arg ref="query"></constructor-arg>
</bean>
<bean id="query" class="com.qls.impl.SlayDragonQuest">
<!-- collaborators and configuration for this bean go here -->
<constructor-arg value="#{T(System).out}"/>
</bean>
<!-- more bean definitions go here -->
</beans>

//spring-julythird.xml的代码如下:

 <?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.xsd">
<!--this is constructor injection-->
<!--the act of creating associations between application components is commonly referred to
as wiring-->
<bean id="knight" class="com.qls.impl.BraveKnight">
<!-- collaborators and configuration for this bean go here -->
<constructor-arg ref="query"></constructor-arg>
</bean>
<bean id="query" class="com.qls.impl.SearchHillQuest">
<constructor-arg value="#{T(System).out}"/>
</bean>
<!-- more bean definitions go here -->
</beans>

//Query接口的代码如下:

 package com.qls.inter;

 /**
* Created by ${秦林森} on 2017/6/2.
*/
public interface Query {
void query();
void embark();
}

//Knight的代码如下:

 package com.qls.inter;

 /**
* Created by ${秦林森} on 2017/6/2.
*/
public interface Knight {
void embarkOnQuest();
}

//Query接口的实现类的代码如下:

//首先是:SlayDragonQuest的代码如下:

 package com.qls.impl;

 import com.qls.inter.Query;

 import java.io.PrintStream;

 /**
* Created by ${秦林森} on 2017/6/2.
*/
public class SlayDragonQuest implements Query{
private PrintStream stream; public SlayDragonQuest(PrintStream stream) {
this.stream = stream;
}
@Override
public void embark(){
stream.println("Embarking on quest to slay the dragon");
stream.println("ouyangfeng is the most beautiful woman in the world.");
}
@Override
public void query(){
System.out.println("slay dragon quest");
}
}

//其次是SearchHillQuest的代码如下:

 package com.qls.impl;

 import com.qls.inter.Query;

 import java.io.PrintStream;

 /**
* Created by ${秦林森} on 2017/6/3.
*/
public class SearchHillQuest implements Query{
private PrintStream stream; public SearchHillQuest(PrintStream stream) {
this.stream = stream;
} @Override
public void query() { } @Override
public void embark() {
stream.println("the hero search the hill where the damsel was missing");
}
}

//BraveKnight的代码如下:

 package com.qls.impl;

 import com.qls.inter.Knight;
import com.qls.inter.Query;
import org.springframework.context.annotation.Configuration; /**
* Created by ${秦林森} on 2017/6/2.
*/ public class BraveKnight implements Knight{
private Query query; public BraveKnight(Query query) {
this.query = query;
} @Override
public void embarkOnQuest() {
query.embark();
}
}

//测试类的代码如下:

 package com.qls.test;

 import com.qls.inter.Knight;
import org.springframework.context.support.ClassPathXmlApplicationContext; /**
* Created by ${秦林森} on 2017/6/2.
*/
public class Test {
public static void main(String[] args) {
/**
* 加载配置文件的方式:在src下直接写配置文件的名即可,
* 不直接在src下要把前面的包名加上。包名的前面可加也可以不加斜杠/
*/
// ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("/com/config/spring-julythird.xml");
// ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("com/config/spring-julythird.xml");
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-julysecond.xml");
Knight knight = context.getBean(Knight.class);
knight.embarkOnQuest();
context.close(); }
}

spring in action学习笔记一:DI(Dependency Injection)依赖注入之CI(Constructor Injection)构造器注入的更多相关文章

  1. Spring in Action 学习笔记二-DI

    装配bean 2015年10月9日 9:49             Sprng中,对象无需自己负责查找或创建其关联的其他对象.相关,容器负责吧需要相互协作的对象引用赋予各个对象. 创建应用对象之间协 ...

  2. Spring in Action 学习笔记一

    Spring 核心       Spring的主要特性仅仅是 依赖注入DI和面向切面编程AOP       JavaBean 1996.12 Javav 规范针对Java定义了软件组件模型,是简单的J ...

  3. spring in action学习笔记十五:配置DispatcherServlet和ContextLoaderListener的几种方式。

    在spring in action中论述了:DispatcherServlet和ContextLoaderListener的关系,简言之就是DispatcherServlet是用于加载web层的组件的 ...

  4. spring in action 学习笔记十四:用纯注解的方式实现spring mvc

    在讲用纯注解的方式实现springmvc之前先介绍一个类:AbstractAnnotationDispatcherServletInitializer.这个类的作用是:任何一个类继承AbstractA ...

  5. Spring in Action 学习笔记三-AOP

    面向切面的Spring 2015年10月9日 11:30             屏幕剪辑的捕获时间: 2015-10-9 14:30             屏幕剪辑的捕获时间: 2015-10-9 ...

  6. spring in action学习笔记十六:配置数据源的几种方式

    第一种方式:JNDI的方式. 用xml配置的方式的代码如下: 1 <jee:jndi-lookup jndi-name="/jdbc/spittrDS" resource-r ...

  7. spring in action 学习笔记九:如何证明在scope为prototype时每次创建的对象不同。

    spring 中scope的值有四个:分别是:singleton.prototype.session.request.其中session和request是在web应用中的. 下面证明当scope为pr ...

  8. spring in action学习笔记七:@Conditional注解的用法

    @Profile注解是@Conditional注解的一个例子.即@Profile也是用@Conditional注解来实现的. 必须让条件实现Condition这个接口. 下面的案例讲如果环境中有mag ...

  9. spring in action 学习笔记五:@Autowired这个注解如何理解

    @Autowired这个注解的意思就是自动装配.他把一个bean对象自动装配到另一个对象中.下面的案例证明了spring的自动装配. 定义一个Sixi类.代码如下: package com.qls.a ...

随机推荐

  1. IntelliJ IDEA 12详细开发教程(一)思想的转变与新手入门【转】

    转载地址:http://bangqu.com/alicas/blog/433 从事软件开发工作以来,提高自己的开发效率,提高自己编码的规范,提高编码深度层次,这三样一直都是自己努力去追求的事情. 最近 ...

  2. 【转载】C#批量插入数据到Sqlserver中的三种方式

    引用:https://m.jb51.net/show/99543 这篇文章主要为大家详细介绍了C#批量插入数据到Sqlserver中的三种方式,具有一定的参考价值,感兴趣的小伙伴们可以参考一下 本篇, ...

  3. Laravel5.5.x集成Swagger (L5-Swagger) 只讲Laravel5.5.x的集成,laravel其他版本请自行研究或参考github上的说明

    --------上图 截取自Github 官网上的安装参考----------------------------------------------------------------------- ...

  4. c++ tie,ignore

    ignore 一个未指定的类型对象,任何值都可以没有影响地赋值给它.通常使用tie来解压一个元组,作为可以忽略的占位符. #include <iostream> #include < ...

  5. 第一章 UNIX 基础知识

    1.1 Unix体系结构 OS定义为一种软件,它控制计算机硬件资源,提供程序运行环境,一般称其为内核(kernel),它体积小,位于环境中心. 内核的接口为系统调用(system call),共用函数 ...

  6. PHP.25-TP框架商城应用实例-后台2-商品列表页-搜索、翻页、排序

    商品列表页 1.翻页 控制器GoodsController.class.php添加方法lst(),显示列表页 在商品模型GoodsModel.class.php类中添加search方法 /** *实现 ...

  7. Weblogic Linux jar包安装

    环境/工具: 系统:CentOS 7 JDK:Oracle JDK fmw_12.2.1.2.0_wls.jar 0x01.新建普通用户weblogic 在Linux环境下建议使用普通用户安装,web ...

  8. 16,Flask-Migrate

    终于到了Flask-Migrate,之前在学习Flask-SQLAlchemy的时候,Flask支持 makemigration / migrate 吗? 答案在这里该诉你,如果你同时拥有两个三方组件 ...

  9. WPF系列教程——(一)仿TIM QQ界面 - 简书

    原文:WPF系列教程--(一)仿TIM QQ界面 - 简书 TIM QQ 我们先来看一下TIM QQ长什么样,整体可以将界面分为三个部分 TIM QQ 1. 准备 阅读本文假设你已经有XAML布局的基 ...

  10. TP5 中出现 No input file specified

    之前用php5.4 更新至php7之后原tp5项目出现 No input file specified 修改方法: 打开public目录下的.htaccess文件,把:RewriteRule ^(.* ...