平常的Java开发中,程序员在某个类中需要依赖其它类的方法。

通常是new一个依赖类再调用类实例的方法,这种开发存在的问题是new的类实例不好统一管理。

Spring提出了依赖注入的思想,即依赖类不由程序员实例化,而是通过Spring容器帮我们new指定实例并且将实例注入到需要该对象的类中。

依赖注入的另一种说法是"控制反转"。通俗的理解是:平常我们new一个实例,这个实例的控制权是我们程序员。

而控制反转是指new实例工作不由我们程序员来做而是交给Spring容器来做。

1.Set注入

构建一个Student对象

package cn.happy.entity;

/**
* Created by CKW on 2017/3/19.
*/
public class Student {
private String sname;
private Integer sage; public Integer getSage() {
return sage;
} public void setSage(Integer sage) {
this.sage = sage;
} public String getSname() {
return sname;
} public void setSname(String sname) {
this.sname = sname;
} }

在配置applicationContext.xml中:

    <!--set 注入  prototype  原型   singletion  单例-->
<bean id="stu" class="cn.happy.entity.Student" scope="prototype">
<property name="sname" value="张三"></property>
<property name="sage" value=""></property>
</bean>

测试类中:

    //被Spring管理的bean默认都是单例的
@Test
public void myTest1(){
//ac 就是Spring容器
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
Student stu=(Student) ac.getBean("stu");
Student stu1=(Student) ac.getBean("stu");
System.out.println(stu+"\n"+stu1);
}

2.构造器注入

在对象中添加构造

配置中:

    <!--构造注入-->
<bean id="car1" class="cn.happy.entity.Car">
<property name="cname" value="图驴子"></property>
</bean>
<bean id="stu1" class="cn.happy.entity.Student">
<!--()创建构造器注入,如果主类有带参的构造方法则需添加此配置-->
<constructor-arg index="" value="哇哈哈"></constructor-arg>
<constructor-arg index="" value=""></constructor-arg>
<constructor-arg index="" ref="car1"></constructor-arg>
</bean>

测试类:

    //构造注入
@Test
public void myTest2(){
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
Student stu1=(Student) ac.getBean("stu1");
Student stu2=(Student) ac.getBean("stu2");
System.out.println("构造:"+stu1); }

3.空间命名注入

<?xml version="1.0" encoding="UTF-8"?>
<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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
">
    <!--命名空间P注入-->
<bean id="car2" class="cn.happy.entity.Car">
<property name="cname" value="毛驴"></property>
</bean>
<bean id="stu2" class="cn.happy.entity.Student" p:sname="李四" p:sage="" p:car-ref="car2"></bean>
    //构造注入   命名空间注入
@Test
public void myTest2(){
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
Student stu1=(Student) ac.getBean("stu1");
Student stu2=(Student) ac.getBean("stu2");
System.out.println("构造:"+stu1+"\n命名空间:"+stu2); }

4.集合注入

    <!--list集合属性注入-->
<bean id="collection1" class="cn.happy.entity.MyCollection">
<property name="list">
<list>
<value>哈哈</value>
<value>呵呵</value>
<value>嘿嘿</value>
</list>
</property>
</bean> <!--set集合属性注入-->
<bean id="collection2" class="cn.happy.entity.MyCollection">
<property name="set">
<set>
<value>哈哈</value>
<value>呵呵</value>
<value>嘿嘿</value>
</set>
</property>
</bean> <!--Map集合属性注入-->
<bean id="collection3" class="cn.happy.entity.MyCollection">
<property name="map">
<map>
<entry key="">
<value>呵呵</value>
</entry>
<entry key="">
<value>哈哈</value>
</entry>
<entry key="">
<value>嘿嘿</value>
</entry>
</map>
</property>
</bean>

5.注解注入

package cn.happy.entity;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service; /**
* Created by CKW on 2017/3/22.
*/
@Component("car") //不分层
/*@Repository //dao层*/
/*@Service //biz层*/
/*@Controller //action层*/
public class Car {
@Value("特斯拉")
private String cname; @Override
public String toString() {
return getCname();
} public Car() {
} public Car(String cname) {
this.cname = cname;
} public String getCname() {
return cname;
} public void setCname(String cname) {
this.cname = cname;
}
}
package cn.happy.entity;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; import javax.annotation.Resource; /**
* Created by CKW on 2017/3/22.
*/ @Component("student")
public class Student {
@Value("撒打发")
private String sname;
@Value("")
private Integer sage;
//jdk注解
// @Resource
@Autowired
@Qualifier("car")
private Car car; @Override
public String toString() {
return "name="+getSname()+",age="+getSage()+",car="+getCar();
} public Car getCar() {
return car;
} public void setCar(Car car) {
this.car = car;
} public Student() { } public String getSname() {
return sname;
} public Student(String sname, Integer sage, Car car) {
this.sname = sname;
this.sage = sage;
this.car = car;
} public void setSname(String sname) {
this.sname = sname;
} public Integer getSage() {
return sage;
} public void setSage(Integer sage) {
this.sage = sage;
}
}

在配置applicationContext.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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
">
  <!--注解-->
<!--配置包扫描器-->
<context:component-scan base-package="cn.happy.entity"></context:component-scan>

测试类:

    //注解
@Test
public void myTest4(){
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
Student stu=(Student)ac.getBean("student");
System.out.println(stu.getCar().getCname());
}

Spring多种方式实现依赖注入的更多相关文章

  1. Spring——多种方式实现依赖注入

    在Spring的XML配置中,只有一种声明bean的方式:使用<bean>元素并指定class属性.Spring会从这里获取必要的信息来创建bean. 但是,在XML中声明DI时,会有多种 ...

  2. IOC和AOP使用扩展 多种方式实现依赖注入

    多种方式实现依赖注入 1.Spring 使用setter访问器实现对属性的赋值, 2.Spring 构造constructor方法赋值, 3.接口注入 4.Spring P命名空间注入直接量 sett ...

  3. Spring - lookup-method方式实现依赖注入

    引言 假设一个单例模式的bean A需要引用另外一个非单例模式的bean B,为了在我们每次引用的时候都能拿到最新的bean B,我们可以让bean A通过实现ApplicationContextWa ...

  4. 多种方式实现依赖注入及使用注解定义bean

    构造注入 如何给构造方法中的参数注入方法呢如下 首先bean代码如下 package cn.pojo; public class Greeting { /** * 说的话 */ private Str ...

  5. Ioc和Aop扩展--多种方式实现依赖注入(构造注入,p命名空间注入,集合类型注入,注入null和注入空值)

    构造注入 语法: <constructor-arg>    <ref bean="bean的id"/> </constructor-arg> 1 ...

  6. Spring源码剖析依赖注入实现

    Spring源码剖析——依赖注入实现原理 2016年08月06日 09:35:00 阅读数:31760 标签: spring源码bean依赖注入 更多 个人分类: Java   版权声明:本文为博主原 ...

  7. (转)Spring读书笔记-----Spring核心机制:依赖注入

    Java应用(从applets的小范围到全套n层服务端企业应用)是一种典型的依赖型应用,它就是由一些互相适当地协作的对象构成的.因此,我们说这些对象间存在依赖关系.加入A组件调用了B组件的方法,我们就 ...

  8. 回客科技 面试的 实现ioc 容器用到的技术,简述BeanFactory的实现原理,大搜车面试的 spring 怎么实现的依赖注入(DI)

    前言:这几天的面试,感觉自己对spring 的整个掌握还是很薄弱.所以需要继续加强. 这里说明一下spring的这几个面试题,但是实际的感觉还是不对的,这种问题我认为需要真正读了spring的源码后说 ...

  9. ExpandoObject与DynamicObject的使用 RabbitMQ与.net core(一)安装 RabbitMQ与.net core(二)Producer与Exchange ASP.NET Core 2.1 : 十五.图解路由(2.1 or earler) .NET Core中的一个接口多种实现的依赖注入与动态选择看这篇就够了

    ExpandoObject与DynamicObject的使用   using ImpromptuInterface; using System; using System.Dynamic; names ...

随机推荐

  1. linux 安装mysql 5.7

    1.下载安装包http://dev.mysql.com/downloads/mysql/#downloads推荐下载通用安装方法的TAR包(http://cdn.mysql.com//Download ...

  2. 剑指Offer的学习笔记(C#篇)-- 二维数组中的查找

    题目描述 在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序.请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数 ...

  3. 支持通配符查询的k-gram索引

    k-gram索引的通配符查询处理技术称为k-gram索引. 一个k-gram代表由k个字符组成的序列.对于词项castle来说,cas.ast.stl都是3-gram.我们用特殊的字符$来标识词项的开 ...

  4. react-native-video的使用

    /** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow */ impo ...

  5. sublime安装与使用

    整理sublime的安装和使用的步骤,以及一些常用插件的安装.配置.使用.免得每次换环境都需要重新上网查找一堆资料. 前言目前使用的版本是sublime text3.选择sublime的理由 subl ...

  6. js json与字符串相互转换

    JSON.parse(jsonstr); //可以将json字符串转换成json对象 JSON.stringify(jsonobj); //可以将json对象转换成json对符串

  7. python大战机器学习——数据降维

    注:因为公式敲起来太麻烦,因此本文中的公式没有呈现出来,想要知道具体的计算公式,请参考原书中内容 降维就是指采用某种映射方法,将原高维空间中的数据点映射到低维度的空间中 1.主成分分析(PCA) 将n ...

  8. 070 Climbing Stairs

    你正在爬楼梯.需要 n 步你才能到达顶部.每次你可以爬 1 或 2 个台阶.你有多少种不同的方式可以爬到楼顶呢?注意:给定 n 将是一个正整数.示例 1:输入: 2输出: 2说明: 有两种方法可以爬到 ...

  9. this、apply、call的指向

    1.关于this this它总是返回一个对象,是指调用当前函数的对象,由于对象的属性可以赋给另一个对象,所以属性所在的当前对象是可变的,即this的指向是可变的. var person={ name: ...

  10. kindeditor编辑器和图片上传独立分开的配置细节

    关于kindeditor编辑器上传按钮的异步加载最关键的部署问题,它的上传图片的组件都已经封装得很好了的,只需要监听到页面按钮的点击事件给编辑器对象传递一些对应的初始化参数即可显示图片上传的弹窗实现异 ...