SPR4: 依赖注入的三种方式
4.1 构造器注入
即在配置文件中,通过bean标签,使用 constructor-arg 子标签实现。
4.2 setter()注入
4.2.1 简介
依赖注入一词,依赖 指的是bean对象的创建依赖于Spring容器。注入 则指的是bean里面的属性值,由SPring传递。
4.2.2 环境配置
Address:
package com.yun.pojo;public class Address {private String address;public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}
}
Student:
package com.yun.pojo;import java.util.*;public class Student {private String name;private Address address;private String[] books;private List<String> hobbies;private Map<String,String> card;private Set<String> games;private String wife;private Properties info;public String getName() {return name;}public void setName(String name) {this.name = name;}public Address getAddress() {return address;}public void setAddress(Address address) {this.address = address;}public String[] getBooks() {return books;}public void setBooks(String[] books) {this.books = books;}public List<String> getHobbies() {return hobbies;}public void setHobbies(List<String> hobbies) {this.hobbies = hobbies;}public Map<String, String> getCard() {return card;}public void setCard(Map<String, String> card) {this.card = card;}public Set<String> getGames() {return games;}public void setGames(Set<String> games) {this.games = games;}public String getWife() {return wife;}public void setWife(String wife) {this.wife = wife;}public Properties getInfo() {return info;}public void setInfo(Properties info) {this.info = info;}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", address=" + address +", books=" + Arrays.toString(books) +", hobbies=" + hobbies +", card=" + card +", games=" + games +", wife='" + wife + '\'' +", info=" + info +'}';}
}
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"xsi:schemaLocation="http://www.springframework.org/schema/beanshttps://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="student" class="com.yun.pojo.Student"><property name="name" value="张三"/></bean></beans>
测试接口:
package com.yun;import com.yun.pojo.Student;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class MyTest {@Testpublic void test(){ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");Student student = (Student)context.getBean("student");System.out.println(student);}
}
4.2.3 各类型的依赖注入
普通类型注入:
<bean id="student" class="com.yun.pojo.Student"><property name="name" value="张三"/></bean>
对象属性注入:
<bean id="address1" class="com.yun.pojo.Address"><property name="address" value="武汉"/></bean><bean id="student" class="com.yun.pojo.Student"><!-- 对象属性注入--><property name="address" ref="address1"/></bean>
数组属性注入:
<bean id="student" class="com.yun.pojo.Student"> <!-- 数组注入--><property name="books"><array><value>斗破苍穹</value><value>斗罗大陆</value><value>善良的死神</value><value>仙逆</value></array></property></bean>
List属性注入:
<bean id="student" class="com.yun.pojo.Student"><!--list属性注入--><property name="hobbies"><list><value>打游戏</value><value>听歌</value><value>看电影</value></list></property></bean>
map属性注入:
<bean id="student" class="com.yun.pojo.Student"><!-- map属性注入--> <property name="card"><map><entry key="身份证" value="中国公民身份证"/><entry key="银行卡" value="中国农业银行储蓄卡"/><entry key="信用卡" value="建设银行龙卡"/></map></property></bean>
Set属性注入:
<bean id="student" class="com.yun.pojo.Student"> <!-- set属性注入--><property name="games"><set><value>绝地求生</value><value>GTA5</value></set></property></bean>
null属性注入:
<bean id="student" class="com.yun.pojo.Student"><!--null属性注入--><property name="wife"><null/></property></bean>
Properties属性注入:
<bean id="student" class="com.yun.pojo.Student"> <!-- Properties属性注入--><property name="info"><props><prop key="学号">202545877</prop><prop key="性别">男</prop></props></property></bean>
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"xsi:schemaLocation="http://www.springframework.org/schema/beanshttps://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="address1" class="com.yun.pojo.Address"><property name="address" value="武汉"/></bean><bean id="student" class="com.yun.pojo.Student"><!-- 普通类型注入--><property name="name" value="张三"/><!-- 对象属性注入--><property name="address" ref="address1"/> <!-- 数组注入--><property name="books"><array><value>斗破苍穹</value><value>斗罗大陆</value><value>善良的死神</value><value>仙逆</value></array></property> <!-- list属性注入--><property name="hobbies"><list><value>打游戏</value><value>听歌</value><value>看电影</value></list></property> <!-- map属性注入--><property name="card"><map><entry key="身份证" value="中国公民身份证"/><entry key="银行卡" value="中国农业银行储蓄卡"/><entry key="信用卡" value="建设银行龙卡"/></map></property> <!-- set属性注入--><property name="games"><set><value>绝地求生</value><value>GTA5</value></set></property> <!--null属性注入--><property name="wife"><null/></property> <!-- Properties属性注入--><property name="info"><props><prop key="学号">202545877</prop><prop key="性别">男</prop></props></property></bean> </beans>
输出结果:
Student{name='张三', address=Address{address='武汉'}, books=[斗破苍穹, 斗罗大陆, 善良的死神, 仙逆], hobbies=[打游戏, 听歌, 看电影], card={身份证=中国公民身份证, 银行卡=中国农业银行储蓄卡, 信用卡=建设银行龙卡}, games=[绝地求生, GTA5], wife='null', info={学号=202545877, 性别=男}}
总结: arry、list、set、Properties 都是通过标签包含传值,并不是所谓的属性传值。
4.3 其他注入
4.3.1 P命名空间注入
约束:
xmlns:p="http://www.springframework.org/schema/p"
例子:
User.java
package com.yun.pojo;public class User {private String name;private int age;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "User{" +"name='" + name + '\'' +", age=" + age +'}';}
}
beans.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:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beanshttps://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="user" class="com.yun.pojo.User" p:name="李四" p:age="20"/></beans>
<!--导入约束,使用P标签-->
提示: 在Spring配置文件applicationContext.xml中,使用import导入bean.xml,或者将beans.xml作为Spring配置文件。
测试接口:
package com.yun;import com.yun.pojo.Student;
import com.yun.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class MyTest {@Testpublic void test(){ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");User user = context.getBean("user", User.class);System.out.println(user);}
}
总结: p命名空间的依赖注入方式,本质上应该依旧是setter()注入。
4.3.2 c命名空间注入
User.java
package com.yun.pojo;public class User {private String name;private int age;public User(String name, int age) {this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "User{" +"name='" + name + '\'' +", age=" + age +'}';}
}
bean.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:c="http://www.springframework.org/schema/c"xsi:schemaLocation="http://www.springframework.org/schema/beanshttps://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="user" class="com.yun.pojo.User" c:name="王五" c:age="20"/></beans>
提示: 在Spring配置文件applicationContext.xml中,使用import导入bean.xml,或者将beans.xml作为Spring配置文件。
测试接口:
package com.yun;import com.yun.pojo.Student;
import com.yun.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class MyTest {@Testpublic void test(){ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");User user = context.getBean("user", User.class);System.out.println(user);}
}
总结: c命名空间的依赖注入,本质上是构造器注入,因此实体类必须拥有有参构造。
4.4 bean的作用域
4.4.1 简介
Spring在创建bean对象之后,bean拥有着6种作用域:singeleton、prototype、request、session、application、websocket 。
4.4.2 singeleton单例模式
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:c="http://www.springframework.org/schema/c"xsi:schemaLocation="http://www.springframework.org/schema/beanshttps://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="user" class="com.yun.pojo.User" c:name="王五" c:age="20" scope="singleton"/>
</beans>
测试接口:
package com.yun;import com.yun.pojo.Student;
import com.yun.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class MyTest {@Testpublic void test(){ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");User user = context.getBean("user", User.class);User user1 = context.getBean("user", User.class);System.out.println(user==user1);}
}
提示: 输出结果为 true ,因为当前的Bean的作用域设置为singleton,并且Spring的bean作用域默认为singleton,所以,从容器内获取的实体类对象,都会受singleton单例的影响,只会创建一个实例。
4.4.3 prototype原型模式
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:c="http://www.springframework.org/schema/c"xsi:schemaLocation="http://www.springframework.org/schema/beanshttps://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="user" class="com.yun.pojo.User" c:name="王五" c:age="20" scope="prototype"/>
</beans>
测试接口:
package com.yun;import com.yun.pojo.Student;
import com.yun.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class MyTest {@Testpublic void test(){ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");User user = context.getBean("user", User.class);User user1 = context.getBean("user", User.class);System.out.println(user==user1);}
}
提示: 输出结果为 flase ,prototype 原型模式,每一次从容器内获取对象,都会创建一个新的对象。
4.4.4 request、session、application
此三种,只会在web开发中使用,具体详情需要查询官方文档。
写在最后,Spring学到这里,依旧有着不小的疑问,例如IOC注入到底有什么用;当我们使用bean进行依赖注入时,会不会把数据写死了;如果不是,那么IOC注入到底该怎么用。
SPR4: 依赖注入的三种方式相关推荐
- 05.bean依赖注入的三种方式
05.bean依赖注入的三种方式 1.概述 依赖注入 DI(Dependency Injection):它是 Spring 框架核心 IOC 的具体实现. 在编写程序时,通过控制反转,把对象的创建交给 ...
- spring依赖注入的三种方式以及优缺点
spring依赖注入的三种方式以及优缺点 一.依赖注入的三种方式 1.通过构造器注入.(spring4.3之后,推荐使用) 2.通过setter注入.(spring4.3之前,推荐使用) 3通过fil ...
- php依赖注入的三种方式
控制反转(Inversion of Control,缩写为IoC),是面向对象编程中的一种设计原则,可以用来减低计算机代码之间的耦合度.其中最常见的方式叫做依赖注入(Dependency Inject ...
- Spring系列之依赖注入的三种方式
目录 一.依赖注入方式 1.使用属性的setXXX方法注入 2.构造函数注入 (1)按类型匹配入参type (2)按索引匹配入参index (3)联合使用类型和索引匹配入参[type和index一起使 ...
- Spring注解依赖注入的三种方式的优缺点以及优先选择
当我们在使用依赖注入的时候,通常有三种方式: 1.通过构造器来注入: 2.通过setter方法来注入: 3.通过filed变量来注入: 那么他们有什么区别吗?应该选择哪种方式更好? 代码示例: Con ...
- 依赖注入的三种方式_Spring IoC是如何进行依赖注入的
依赖注入(DI) DI(Dependency Injection),Spring IoC 不是一种技术,而是一种思想,通过这种思想,能够指导我们设计出松耦合的程序代码.而Spring IoC这个思想的 ...
- Spring依赖注入的三种方式(好的 坏的和丑的)
关于spring bean三种注入方式的优缺点对比,翻译自Spring DI Patterns: The Good, The Bad, and The Ugly,水平有限,如有错误请指正. Sprin ...
- 依赖注入的三种方式_一起学Spring之三种注入方式及集合类型注入
本文主要讲解Spring开发中三种不同的注入方式,以及集合数据类型的注入,仅供学习分享使用,如有不足之处,还请指正. 概述 Spring的注入方式一共有三种,如下所示: 通过set属性进行注入,即通过 ...
- 依赖注入的三种方式_ASP.NET Core技术研究-探秘依赖注入框架
ASP.NET Core在底层内置了一个依赖注入框架,通过依赖注入的方式注册服务.提供服务.依赖注入不仅服务于ASP.NET Core自身,同时也是应用程序的服务提供者. 毫不夸张的说,ASP.NET ...
最新文章
- linux终端terminal个性化配置(转)
- Maven在windows下的安装
- 使用curl上传带有文件的POST数据
- MyBatis:参数传递 [转]
- Android__Context
- 给 TComboBox 添加图标 - 回复 heyongan 的问题
- java的平方分之x的平方加xy_Java面试宝典_基础编程练习题_完全平方数
- boost::asio
- Java System.in.skip()的作用
- vscode不能跳转_vscode-goto-node-modules 一个快速定位 node 模块的 vscode 插件
- [渣译文] SignalR 2.0 系列: SignalR简介
- Ubuntu 11.04上安装jdk1.6+oracle 11g笔记
- VB6.0 组织json对象并生成json字符串
- matlab绘制雷达图
- 从零开始变成一个脚本小子002-初窥密码2
- 推荐系统序列化建模总结
- 如何写出自媒体10W+爆文?
- 通过session实现用户的登录与登出功能
- 云计算:SaaS、PaaS、IaaS、CaaS并不神秘
- 面向对象以及三大特性
热门文章
- 怎样用c语言计算出自己的出生天数,新手编的小程序:计算年龄和出生后经历的天数的小程序...
- 统计学和python结合起来打的比赛_数学与Python有机结合及统计学、微积分、线性代数相关资源、图形软件...
- CSS学习之相对定位和绝对定位
- iphone 视频播放m3u8问题
- 【Android】Coil:为kotlin而生的图片库
- 大乐透历史数据走势图查询工具
- 天天学Python(一)—鸭子模型
- NLog详细教程-2022/12/01
- NLog简单使用教程
- ygo游戏王卡组_游戏王卡组第六弹:游戏衍生卡组最风光的卡组之一,完全碾压社长...