Spring IoC容器(一)

 IoC,Inversion of Control 控制反转,是一个过程。仅通过构造函数、工厂方法或在对象实例化后在对象实例上设置属性来定义其依赖关系。容器负责这些工作,这个过程从本质上来说是bean本身的反向,因此称为反向控制。

1 容器

负责实例化、配置及装配bean。容器从配置元数据那获取该怎么实例化、配置及装配bean。而配置来源主要有三个:1)XML;2)java注释;3)java代码。xml比较常用。

@Configuration // 将一个普通类标志为IoC容器
public class CustomConfig {@Bean // 定义一个beanpublic User customUser() {return new User();}
}private static void test1() {AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(CustomConfig.class);User user = context.getBean(User.class);System.out.println(user);
}

上面代码展示了java代码配置bean的方式。通过AnnotationConfigApplicationContext来获取容器。

图 ApplicationContext的方法及实现类

BeanFactory 接口提供了管理Bean的方法,而ApplicationContext继承了该接口,并有以下扩展:

1)更容易与Spring 的aop集成。

2)消息资源处理。

3)事件发布。

4)针对web项目,提供了特定的子类。

图 ApplicationContext的方法及实现类

2 Bean

构成程序主干并由IoC容器管理的对象称为bean。

在模块化开发中,不同模块的容器可能存在依赖了同一bean的bean。有时,我们考虑到扩展或者在某个模块中有特定的命名规范,所依赖的这个bean的命名可能会不同。 比如模块A、B依赖同一个数据源配置bean。 在模块A中该bean命名为datasourceA,在模块B中命名为datasourceB。这时候需要用到别名。

<!--数据源,common.xml-->
<bean id="datasource" class="dao.BaseDao"/><!--模块A a.xml-->
<import resource="dao.xml"/><!—别名-->
<alias name="datasource" alias="datasourceA"/>
<bean id="teacherService" class="service.TeacherService"><property name="baseDao" ref="baseDao"/>
</bean>

2.1 实例化

xml配置中,实例化bean有三种方式:1)构造函数;2)静态工厂方法;3)bean的工厂方法。

public class GoodsDao {
}public class GoodsService {public GoodsDao makeGoodsDao() {return new GoodsDao();}
}public class StaticFactory {public static GoodsService makeGoodsService() {return new GoodsService();}
}<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" default-lazy-init="true"><!--构造函数实例化--><bean id="goodsService" class="instantiating.GoodsService"/><!--静态工厂实例化,class为该工厂的类--><bean id="goodsService2" class="instantiating.StaticFactory" factory-method="makeGoodsService"/><!--bean的工厂实例化--><bean id="goodsDao" factory-bean="goodsService" factory-method="makeGoodsDao"/>
</beans>

3 依赖

依赖是指对象在运行中需要用到的其他对象。在IoC中由容器负责注入。注入方式有两种:1)构造函数;2)set方法。

public class OtherDao {
}public class ReportDao {
}public class ReportService {private ReportDao reportDao;private String name;private Double num;public ReportService(ReportDao reportDao, String name, Double num) {this.reportDao = reportDao;this.name = name;this.num = num;}private Properties dataProperties;private Map<String, String> stockInfoMap;private List<String> links;private OtherDao otherDao;public void setDataProperties(Properties dataProperties) {this.dataProperties = dataProperties;}public void setStockInfoMap(Map<String, String> stockInfoMap) {this.stockInfoMap = stockInfoMap;}public void setLinks(List<String> links) {this.links = links;}public void setOtherDao(OtherDao otherDao) {this.otherDao = otherDao;}@Overridepublic String toString() {return "ReportService{" +"reportDao=" + reportDao +", name='" + name + '\'' +", num=" + num +", dataProperties=" + dataProperties +", stockInfoMap=" + stockInfoMap +", links=" + links +", otherDao=" + otherDao +'}';}public static void main(String[] args) {ApplicationContext applicationContext = new ClassPathXmlApplicationContext("dependency.xml");ReportService reportService = applicationContext.getBean(ReportService.class);System.out.println(reportService);}
}<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" default-lazy-init="true"><bean id="reportDao" class="dependency.ReportDao"/><bean id="reportService" class="dependency.ReportService">
<!--        constructor-arg 为构造函数参数,参数可以依赖其他bean,也可以是基本类似--><constructor-arg name="reportDao" ref="reportDao"/><constructor-arg name="name" value="reportService层"/><constructor-arg name="num" value="103.4"/>
<!--        set方法,来注入参数-->
<!--        Properties类型--><property name="dataProperties"><props><prop key="host">localhost</prop><prop key="username">admin</prop><prop key="password">123</prop></props></property>
<!--        Map类型--><property name="stockInfoMap"><map><entry key="name" value="中国平安"/><entry key="stock" value="601318.sh"/></map></property>
<!--        List类型--><property name="links">
<!--            空值--><null /></property><property name="otherDao">
<!--            内部bean,可以不要id或者name,不会被其他bean依赖--><bean class="dependency.OtherDao"/></property></bean>
</beans>

3.1 depends-on与懒加载

容器创建一个bean时,会先创建起依赖的bean。但是有时两个bean直接没有直接依赖,但是希望在创建这个bean之前,先创建其他的bean。可用depends-on来完成这个需求:

<bean id="teacherDao" class="dao.TeacherDao" depends-on="userDao,baseDao"/>

在创建teacherDao这个bean之前,会先创建userDao及baseDao这两个bean。

在容器中,默认会在项目加载时把所有的bean都创建完成,这样做的好处是某个bean的配置错误能在运行时被发现。但是有时不希望创建所有的bean,希望当要使用这个bean时再来创建,default-lazy-init  懒加载属性可以作用于全局的beans,也可以作用于单个的beans。当值为true时,bean在第一次使用时才会被创建。

3.2 方法注入

假如bean1的某个方法,在每次调用时都需要一个特定的bean2(不是bean1的直接依赖,即非bean1的字段)。传统方法是,可以在该方法中通过ApplicationContext获取bean2。这是这样加大了耦合度,容器提供了Lookup标签来实现此类需求:

public class Bean2 {
}public class Bean1 {private final static ApplicationContext applicationContext = new ClassPathXmlApplicationContext("method.xml");/*** 传统方式*/public void showBean2OfTradition() {Object bean2 = applicationContext.getBean("bean2");System.out.println(bean2);}/*** Lookup 方法*/public Bean2 getBean2() {return null;}public static void main(String[] args) {Bean1 bean1 = applicationContext.getBean(Bean1.class);bean1.showBean2OfTradition();System.out.println(bean1.getBean2());}
}<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" default-lazy-init="true"><bean id="bean1" class="method.Bean1">
<!--        会覆盖原getBean2方法,直接返回bean2--><lookup-method name="getBean2" bean="bean2"/></bean><bean id="bean2" class="method.Bean2"/>
</beans>

4 作用域

bean 也可以指定作用域(生命周期),Spring支持六种作用域。bean的scope属性来指定该bean的作用域。

singleton

默认作用域。不同容器生成的bean不同。

prototype

在同一容器中,不同bean依赖的bean被创建的实例不同。

request

每次请求都会创建不同的bean。

session

每个session都会创建不同 bean。

application

每个servletContext生成不同的bean。

websocket

每个websocket连接生成不同的bean。

表 spring 的六种bean的作用域

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/654976.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

C语言入门(二)、每日Linux(三)——gcc命令,通过gcc命令熟悉C语言程序实现的过程

使用gcc编译C语言程序 C语言程序实现的过程gcc命令基础用法常用选项编译和汇编选项&#xff1a;优化选项&#xff1a;调试选项&#xff1a;链接选项&#xff1a;警告选项&#xff1a; 实验对于-o选项 通过gcc命令熟悉C语言程序的执行过程1.预处理2.编译阶段3.汇编阶段4.链接阶段…

牛客周赛round30D题讲解(公式推导)

写的时候题目理解错了(*/ω&#xff3c;*) 登录—专业IT笔试面试备考平台_牛客网 #include <bits/stdc.h>using ll long long;int main(){std::ios::sync_with_stdio(false);std::cin.tie(nullptr);ll x, y, l, r;std::cin >> x >> y >> l >>…

Day 34 | 贪心 1005.K次取反后最大化的数组和 、 134. 加油站、 135. 分发糖果

1005.K次取反后最大化的数组和 题目 文章讲解 视频讲解 思路&#xff1a;要按照绝对值大小进行排序&#xff0c;负数转换后还不到k个选择最小值不断反转 class Solution {public int largestSumAfterKNegations(int[] nums, int k) {nums IntStream.of(nums).boxed().sorte…

大白话解析LevelDB 4: 查找一个 Key

文章目录 查询一个 Key查找 Key 的入口: DBImpl::Get(const ReadOptions& options, const Slice& key, std::string* value)从 MemTable 中查找从 Immutable MemTable 中查找从 SST 中查找 查询一个 Key 查找 Key 的入口: DBImpl::Get(const ReadOptions& options…

Python爬虫---scrapy的post请求

爬虫文件&#xff1a; import scrapyclass TestpostSpider(scrapy.Spider):name "testpost"allowed_domains ["fanyi.baidu.com"]# post 请求如果没有参数&#xff0c;那么这个请求将没有任何意义&#xff0c;所以start_urls也没有用了&#xff0c;pars…

Mysql 索引优化

Mysql 索引优化 mysql如何选择使用索引。 select *from user where username a and password b如果useranme和password都是普通索引&#xff0c;那么他们会把2个索引都查出来&#xff0c;然后在把他们的交集拿出来 如果username是唯一索引&#xff0c;password是普通索引&…

探究React中的非受控组件:自由而简便的表单处理

探究React中的非受控组件&#xff1a;自由而简便的表单处理 在React中&#xff0c;我们常听到"受控组件"的概念&#xff0c;但同样存在一种自由度更高、处理简便的形式——非受控组件。本文将深入介绍非受控组件的使用&#xff0c;通过代码片段中的登录表单实例&…

Java 面试题之 IO(二)

字符流 文章目录 字符流Reader&#xff08;字符输入流&#xff09;Writer&#xff08;字符输出流&#xff09; 文章来自Java Guide 用于学习如有侵权&#xff0c;立即删除 不管是文件读写还是网络发送接收&#xff0c;信息的最小存储单元都是字节。 那为什么 I/O 流操作要分为字…

状态管理与导航守卫

为什么要用vuex&#xff1f; 进行统一的状态管理&#xff0c;解决不同组件共享数据的问题。 如何使用vuex&#xff1f; 1.安装引入 npm install vuex --save 2.注册到vue中 import Vue from vue import Vuex from vuexVue.use(Vuex)3.实例化vuex的store export default new Vue…

算法训练营总结

目录 收获思考感悟后续 收获 不知不觉&#xff0c;已经跟着训练营刷了两个月的题。 之前也跟着代码随想录刷了一大半&#xff0c;因为出差中断没有坚持下来&#xff0c;仅有的基础也扔下了不少。 而这两个月跟着训练营最大的收获就是坚持&#xff0c;不会的题硬啃几天也要搞…

Java 与 JavaScript的区别

Java 与 JavaScript的区别 Java 与 JavaScript&#xff1a;概述Java的特点JavaScript 的起源JavaScript 的特点Java 与 JavaScript&#xff0c;哪个更好&#xff1f;JavaScript 与 Java 相似吗&#xff1f;Java 与 JavaScript 的区别JavaScript 在服务器端的运行方式是怎样的&a…

网络防御安全知识(第二版)

安全策略 传统的包过滤防火墙 --- 其本质为ACL列表&#xff0c;根据数据报中的特征进行过滤&#xff0c;之后对比规制&#xff0c; 执行动作。 五元组 --- 源IP&#xff0c; 目标IP&#xff0c;源端口&#xff0c; 目标端口&#xff0c;协议 安全策略 --- 相较于ACL的改进之…

网站打不开怎么办?高防IP弹性防护更省心

不管你是什么网站&#xff0c;商城网站、游戏网站或者支付网站都有可能存在被攻击的情况&#xff0c;超过防护就会被打死&#xff0c;网站随即而来就打不开了。网站打不开怎么办&#xff1f;看看是不是网站主机或者服务器被攻击了。攻击的大小不可控&#xff0c;选择高防服务器…

Linux/Delivery

Enumeration nmap 首先扫描目标端口对外开放情况&#xff0c;第一轮扫描发现对外开放了22,80,8065三个端口&#xff0c;端口详细信息如下 nmap -sC -sV -p 22,80,8065 10.10.10.222 nmap显示22端口运行着ssh服务&#xff0c;80端口运行着http服务&#xff0c;8065端口运行的…

微信小程序 如何调用微信支付接口

前提&#xff1a; 小程序为企业小程序 并开通了 微信打款认证 例子&#x1f330;&#xff1a; 我们这里以订单为例子 1.创建订单 朝后端发送订单id 或信息 2.后端生成 时间戳/随机字符/id/后端算法签名 3.将获取到的数据 塞入 wx.requestPayment然后就可以掉起为微信支付…

基于go mod模式创建项目最佳实践

希望能带给你成功的喜悦&#xff01; 除go get、vendor这两种方式外&#xff0c;Go版本在1.11之后推出了go module模式来管理依赖&#xff0c;使用go mod时下载的依赖文件在$GOPATH/pkg/mod/下。本文以两种办法介绍如何创建go mod项目。 目录 goland开启玩法 本地手动创建项目…

【Linux】Linux下多线程

需要云服务器等云产品来学习Linux的同学可以移步/–>腾讯云<–/官网&#xff0c;轻量型云服务器低至112元/年&#xff0c;优惠多多。&#xff08;联系我有折扣哦&#xff09; 文章目录 1. 前置&#xff1a;进程地址空间和页表1.1 如何看待进程地址空间和页表1.2 虚拟地址…

MIAOYUN获评OpenCloudOS社区2023年度优秀贡献企业

近日&#xff0c;OpenCloudOS社区发布了社区年度贡献企业榜单&#xff0c;成都元来云志科技有限公司&#xff08;简称“MIAOYUN”&#xff09;凭借对国产开源的热情&#xff0c;及对操作系统产业的支持&#xff0c;通过兼容适配互认证&#xff0c;为推动OpenCloudOS规模化应用&…

python数据类型-数字类型

1. 整型 整型即整数类型&#xff0c;对应于python中的int类型&#xff0c;包含&#xff1a;0&#xff0c;正整数&#xff0c;负整数 数字前面加上进制修饰符代表该数字是几进制&#xff0c;如0b1010则代表二进制&#xff0c;其输出结果为十进制10。默认不加任何进制修饰符为十…