所谓依赖注入,我觉得说白了其实就是给成员变量赋值,不管这个成员变量是基本类型还是引用类型,Spring中常用的依赖注入方式有两种:

1、构造器注入

2、setter注入

下面通过代码实例说明这两种注入的实现方式。

一、构造器注入

1、构造注入的原理

构造注入是利用类的构造方法,大部分情况下我们是通过类的构造函数(含参数或不含参数)创建一个对象,Spring中也可以通过反射方法通过构造函数完成注入。所以这种注入方式一般是用于引用类型。

2、代码实现

在spring中实现需要三个步骤:

1⃣️创建类,提供构造方法。

 public class Employee {
private Integer id; private String username; private String pwd; private String sex; private String random; public Employee() {
}
   //通过含参数的构造方法进行注入
public Employee(Integer id, String username, String pwd, String sex, String random) {
this.id = id;
this.username = username;
this.pwd = pwd;
this.sex = sex;
this.random = random;
}

2⃣️配置spring文件,如果构造函数含有参数,还需要定义参数。

 <?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"> <!-- 通过构造函数注入 -->
<bean id="employee" class="com.hyc.pojo.Employee">
<constructor-arg name="id" value="2" />
<constructor-arg name="username" value="李四" />
<constructor-arg name="pwd" value="lisi123" />
<constructor-arg name="sex" value="male" />
<constructor-arg name="random" value="32412" />
</bean> </beans>

上面的配置文件中主要有以下几点需要注意:

  • id:通过id获取该bean(资源)
  • class:需要装配的类的全限定名
  • constructor-arg:配置构造函数的参数,属性name是参数名称,value是参数值

注意⚠️:参数类型无需定义,spring会自动转化。因为我的类中定义的id是整形,在配置文件中没有定义数据类型,我debug时发现注入成功之后它已经被转换为Integer类型了。

3⃣️通过spring装配(之后的文章会介绍,本文先以XML方式实现)

 public class SpringIocTest {

     public static void main(String[] args) {
ClassPathXmlApplicationContext context = null;
String xmlPath = "classpath*:spring-iocconfig.xml";
try {
context = new ClassPathXmlApplicationContext(xmlPath);
//装配bean
Employee user = (Employee) context.getBean("employee");
System.out.println(user.getUsername());
} catch (BeansException e) {
System.out.println(e.getMessage());
} finally {
if (null != context) {
context.destroy();
}
}
}
}

上面代码用来测试是否注入成功,ClassPathXmlApplicationContext是通过XML的方式装配bean,其中最重要的是context.getBean("employee")这句,其中的employee就是在配置文件中定义的id,这样就能获取到这个bean实例,下面看以下测试结果(预测应该就是上面配置的李四):

注意⚠️:因为调用了getName方法,所以在定义类的时候需要提供getter方法,我没有贴出来!!

看结果与预测是一致的,并且从打印出的信息看出注入的过程中加载了配置文件获取bean。

上面就是构造注入的实现过程。

二、setter注入

setter注入是Spring中最常使用的注入方式,它是利用java bean中定义的setter方法实现注入。使用构造注入时需要给构造函数传多个参数,如果改用setter方法,就不需要定义构造方法了,只要定义一个无餐构造函数和对应的setter方法即可。setter注入实现的步骤也有三步:

1⃣️创建类,提供无参构造方法和setter方法

 public class Employee {
private Integer id; private String username; private String pwd; private String sex; private String random; public Employee() {
} public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username == null ? null : username.trim();
} public String getPwd() {
return pwd;
} public void setPwd(String pwd) {
this.pwd = pwd == null ? null : pwd.trim();
} public String getSex() {
return sex;
} public void setSex(String sex) {
this.sex = sex == null ? null : sex.trim();
} public String getRandom() {
return random;
} public void setRandom(String random) {
this.random = random == null ? null : random.trim();
}
}

一般定义setter和getter方法,setter设置值,getter获取值。

2⃣️配置bean文件

 <?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"> <!-- 通过setter方法注入-->
<bean id="employee1" class="com.hyc.pojo.Employee">
<property name="id" value="3" />
<property name="username" value="张三" />
<property name="pwd" value="lisi123" />
<property name="sex" value="male" />
<property name="random" value="32412" />
</bean> </beans>

注意⚠️:上面的配置中:

  • id:获取这个bean的标识
  • class:需要注入类的全限定名
  • property:类中的成员变量(属性),需要设置哪些变量的值就设置哪些
  • value:属性值

3⃣️通过spring装配

 public class SpringIocTest {

     public static void main(String[] args) {
ClassPathXmlApplicationContext context = null;
String xmlPath = "classpath*:spring-ioc.xml";
try {
context = new ClassPathXmlApplicationContext(xmlPath);
//装配bean
Employee user = (Employee) context.getBean("employee1");
System.out.println(user.getUsername());
} catch (BeansException e) {
System.out.println(e.getMessage());
} finally {
if (null != context) {
context.destroy();
}
}
}
}

同构造注入中介绍的一样,也是通过XML方式获取bean,只不过为了区分在XML中将bean的id定义为employee1。查看测试结果(预期应该是张三)

结果符合预期,注入成功。

以上就是依赖注入的两种实现方式。

装配SpringBean(一)--依赖注入的更多相关文章

  1. Spring-Bean的依赖注入分析-01

    ###我们先通过一个例子弄明白为什么要使用依赖注入### 1.创建业务层UserService接口及UserServiceImpl实现类(接口代码省略) public class UserServic ...

  2. Java开发学习(七)----DI依赖注入之自动装配与集合注入

    一.自动配置 上一篇博客花了大量的时间把Spring的注入去学习了下,总结起来就两个字麻烦.麻烦在配置文件的编写配置上.那有更简单方式么?有,自动配置 1.1 依赖自动装配 IoC容器根据bean所依 ...

  3. Spring笔记——依赖注入

    依赖注入有三种方式: 1. 使用构造器注入  2. 使用属性setter方法注入 3. 使用Field注入(用于注解方式) 注入依赖对象可以采用手工装配或自动装配,在实际应用中建议使用手工装配,因为自 ...

  4. spring in action学习笔记一:DI(Dependency Injection)依赖注入之CI(Constructor Injection)构造器注入

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

  5. 【10分钟学Spring】:(二)一文搞懂spring依赖注入(DI)

    Spring最基础的特性就是创建bean.管理bean之间的依赖关系.下面通过具体实例演示该如何装配我们应用中的bean. Spring提供了三种主要的装配机制 在xml中进行显示的配置 在Java中 ...

  6. JavaEE互联网轻量级框架整合开发(书籍)阅读笔记(7):装配SpringBean·依赖注入装配

    一.依赖注入的三种方式      在实际环境中实现IoC容器的方式主要分为两大类,一类是依赖查找,依赖查找是通过资源定位,把对应的资源查找回来.另一类则是依赖注入.一般而言,依赖注入可分为3中方式: ...

  7. Spring bean依赖注入、bean的装配及相关注解

    依赖注入 Spring主要提供以下两种方法用于依赖注入 基于属性Setter方法注入 基于构造方法注入 Setter方法注入 例子: public class Communication { priv ...

  8. Spring实战2:装配bean—依赖注入的本质

    主要内容 Spring的配置方法概览 自动装配bean 基于Java配置文件装配bean 控制bean的创建和销毁 任何一个成功的应用都是由多个为了实现某个业务目标而相互协作的组件构成的,这些组件必须 ...

  9. Spring基于的注解自动装配和依赖注入(***)

    #自动装配的小Demo: package com.gyf.annotation; //DAO层 public interface UserDao { public void save(); } pac ...

随机推荐

  1. requestAnimationFrame动画封装

    function Animator(duration, progress) { this.duration = duration; this.progress = progress; this.nex ...

  2. error C2872: 'ULONG_PTR' : ambiguous symbol

    转自VC错误:http://www.vcerror.com/?p=74 问题描述: 错误:error C2872: 'ULONG_PTR' : ambiguous symbol 解决方法: 详细的解决 ...

  3. Andriod Fragment 的作用和基本用法

    1.什么是Fragment: Fragment (片段)在Google Android 开发指南中的解释是:片段是Activity中的一部分,一个Activity中可以有多个Fragment.一个Fr ...

  4. day4:Python列表(list)元组( tuple)字典(dict)

    列表----list 列表:中括号,每个元素用‘,’分割,列表里面也可以嵌套列表,列表里面可以包含数字,字符串,布尔值等,也就是元素的集合 例:test = [2,4,'sun','yao'] #索引 ...

  5. MVC中利用ViewBag传递Json数据时的前端处理方法

    用viewBag传递Json字符串到前端时,json字符串中的“会被转义为& quot,前端处理方法为@Html.Raw(Json.Encode(ViewBag.Data)),再用eval() ...

  6. Java之实现多线程

    保证同步的几种方法: (1) 同步方法,synchronized 关键字修饰方法.由于Java中的每个对象都有一个内置锁,当用该关键词修饰时,内置锁会保护整个方法.在调用该方法前,需要获得内置锁,否则 ...

  7. HttpClientUitl工具类

    public class HttpClient { private CloseableHttpClient httpClient; public HttpClient() { this.httpCli ...

  8. idea设置编码格式utf-8

    settings  >> File Encodings >>如下

  9. 【学术篇】luogu2184贪婪大陆

    题目在这里哦, 戳一下就可以了~ 题目大意: 支持两种操作,区间添加一种新元素,查询区间颜色种数.. 题目标签是线段树啊,我也本来想写一个线段树,后来写不出来……(我太弱了orz) 然后就草率地看了看 ...

  10. Keywords Search HDU2222 AC自动机模板题

    ac自动机说起来很复杂,其实和kmp是一样的思路,都是寻找相同前后缀,减少跳的次数.只要理解了kmp是怎么求next数组的,ac自动机bfs甚至比knp还好写. 这里大致说一下kmp求next数组的方 ...