Spring IOC学习
IoC基础
控制反转IoC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IoC的一种方法,也有人认为DI只是IoC的另一种说法。没有IoC的程序中我们使用面向对象编程对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。
使用多种方式完美的实现了IoC,可以使用XML配置,也可以使用注解,新版本的Spring也可以零配置实现IoC。Spring容器在初始化时先读取配置文件,根据配置文件或元数据创建与组织对象存入容器中,程序使用时再从Ioc容器中取出需要的对象。采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。
ApplicationContext加载配置文件的方式:
当配置文件中的配置很多,不便于修改的时候,有如下几种解决方案:
写法1:
//加载classpath
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext2.xml",”applicationContext2.xml);
写法2:
//加载磁盘路径
ApplicationContext applicationContext = new FileSystemXmlApplicationContext("applicationContext2.xml",”applicationContext2.xml);
写法3:
在主配置文件中,引入其他的配置文件。
<import resource="applicationContext2.xml"/>
BeanFactory与ApplicationContext区别?
ApplicationContext类继承了BeanFactory.
BeanFactory采用了延迟加载,在使用到这个类的时候,getBean()方法的时候才会加载这个类.
ApplicationContext类加载配置文件的时候,创建所有的类.
ApplicationContext对BeanFactory提供了扩展:
* 国际化处理、 事件传递、Bean自动装配、各种不同应用层的Context实现
***** 早期开发使用BeanFactory.
IOC装配Bean(XML)
* IOC:控制反转.将对象的创建权交给Spring.
* DI:依赖注入.DI需要有IOC环境的,DI在创建对象的时候,将对象的依赖的属性,一并注入到类中.
Spring框架Bean实例化的方式:
提供了三种方式实例化Bean.
* 无参数的构造方法实例化
* 静态工厂实例化:
* 实例工厂实例化:
无参数构造方法的实例化:
<!-- 默认情况下使用的就是无参数的构造方法. -->
<bean id="bean1" class="cn.itcast.spring3.demo2.Bean1"></bean>
静态工厂实例化:
<!-- 第二种使用静态工厂实例化 -->
<bean id="bean2" class="cn.itcast.spring3.demo2.Bean2Factory" factory-method="getBean2"></bean>
实例工厂实例化:
<!-- 第三种使用实例工厂实例化 -->
<bean id="bean3" factory-bean="bean3Factory" factory-method="getBean3"></bean>
<bean id="bean3Factory" class="cn.itcast.spring3.demo2.Bean3Factory"/>
Bean的其他配置:
id和name的区别:
id遵守XML约束的id的约束.id约束保证这个属性的值是唯一的,而且必须以字母开始,可以使用字母、数字、连字符、下划线、句话、冒号
name没有这些要求
***** 如果bean标签上没有配置id,那么name可以作为id.
***** 开发中Spring和Struts1整合的时候, /login.
<bean name=”/login” class=””>
现在的开发中都使用id属性即可.
类的作用范围scope:
scope属性 :
* singleton:单例的.(默认的值.)
* prototype:多例的.
* request:web开发中.创建了一个对象,将这个对象存入request范围,request.setAttribute();
* session :web开发中.创建了一个对象,将这个对象存入session范围,session.setAttribute();
* globalSession :一般用于Porlet应用环境.指的是分布式开发.不是porlet环境,globalSession等同于session;
实际开发中主要使用singleton、prototype
Bean的生命周期:
配置Bean的初始化和销毁的方法:
配置初始化和销毁的方法:
* init-method=”setup”
* destroy-method=”teardown”
执行销毁的时候,必须手动关闭工厂,而且只对scope=”singleton”有效.
Bean的生命周期的11个步骤:
1.instantiate bean对象实例化
2.populate properties 封装属性
3.如果Bean实现BeanNameAware 执行setBeanName
4.如果Bean实现BeanFactoryAware 或者ApplicationContextAware 设置工厂setBeanFactory 或者上下文对象setApplicationContext
5.如果存在类实现BeanPostProcessor(后处理Bean),执行postProcessBeforeInitialization
6.如果Bean实现InitializingBean 执行afterPropertiesSet
7.调用<beaninit-method="init"> 指定初始化方法 init
8.如果存在类实现BeanPostProcessor(处理Bean),执行postProcessAfterInitialization
9.执行业务处理
10.如果Bean实现 DisposableBean 执行destroy
11.调用<beandestroy-method="customerDestroy"> 指定销毁方法 customerDestroy
DI:Bean中属性注入的方式
Spring支持构造方法注入、setter方法注入和注解的方式:
1、构造器注入:
<bean id="car" class="cn.itcast.spring3.demo5.Car">
//键值对注入
<!--
<constructor-arg name="name" value="宝马"/>
<constructor-arg name="price" value="1000000"/>
-->
//下标索引加强注入
<constructor-arg index="0" type="java.lang.String" value="奔驰"/>
<constructor-arg index="1" type="java.lang.Double"value="2000000"/>
</bean>
一般情况下,使用构造器方式注入比较少用,更多地采用setter方法。
2、setter方法注入:
* 普通属性:
* <property name=”属性名”value=”属性值”>
* 对象属性:
* <property name=”属性名” ref=”其他类的id或name”>
<bean id="car2" class="cn.itcast.spring3.demo5.Car2">
<!-- <property>标签中name就是属性名称,value是普通属性的值,ref:引用其他的对象 -->
<property name="name" value="保时捷"/>
<property name="price" value="5000000"/>
</bean>
setter方法注入对象属性:
<property name="car2" ref="car2"/>
集合属性的注入:
<bean id="collectionBean"class="cn.itcast.spring3.demo6.CollectionBean">
<!-- 注入List集合 -->
<property name="list">
<list>
<value>童童</value>
<value>小凤</value>
</list>
</property>
<!-- 注入set集合 -->
<property name="set">
<set>
<value>杜宏</value>
<value>如花</value>
</set>
</property>
<!-- 注入map集合 -->
<property name="map">
<map>
<entry key="刚刚" value="111"/>
<entry key="娇娇" value="333"/>
</map>
</property>
另一种写法:(很少用)
<property name="map">
<map>
<entry>
<key><value>复杂写法</value></key>
<value>花费时间多</value>
</entry>
</map>
</property>
<!-- 注入propertie属性文件 -->
<property name="properties">
<props>
<propkey="username">root</prop>
<propkey="password">123</prop>
</props>
</property>
</bean>
3、注解方法注入:
3.1、Spring的注解装配Bean
虽然完全使用注解在开发中并不是特别多,但是在框架整合的时候往往会用到注解的方式。
Spring2.5 引入使用注解去定义Bean
@Component 描述Spring框架中Bean
Spring的框架中提供了与@Component注解等效的三个注解:
@Repository 用于对DAO实现类进行标注
@Service 用于对Service实现类进行标注
@Controller 用于对Controller实现类进行标注
***** 三个注解为了后续版本进行增强的.
3.2、使用注解方式进行Bean的属性注入
* 普通属性:
@Value
* 对象属性:
@AutoWired
@Resource
普通属性;
@Value(value="itcast")
private String info;
对象属性:
@Autowired:自动装配默认使用类型注入.
@Autowired
@Qualifier("userDao") --- 按名称进行注入.
@Autowired
@Qualifier("userDao")
private UserDao userDao;
等价于
@Resource(name="userDao")
private UserDao userDao;
3.3、Bean其他的属性的配置:
配置Bean初始化方法和销毁方法:
* init-method 和destroy-method.
@PostConstruct 初始化
@PreDestroy 销毁
配置Bean的作用范围:
@Scope
名称空间p:注入属性
如果一个类的属性非常的多,从Spring2.5开始,Spring提供了名称空间P来帮我们注入属性。
p:<属性名>="xxx"引入常量值
p:<属性名>-ref="xxx"引用其它Bean对象
一个标签注入多个属性
引入名称空间:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="car2" class="cn.itcast.spring3.demo5.Car2" p:name="宝马" p:price="400000"/>
<bean id="person" class="cn.itcast.spring3.demo5.Person" p:name="童童" p:car2-ref="car2"/>
SpEL:属性的注入
Spring3.0开始,还提供了一种新的注入方式:SpEL(Spring Expression Language)表达式注入。
语法:#{表达式}
<bean id=""value="#{表达式}">
<bean id="car2" class="cn.itcast.spring3.demo5.Car2">
<property name="name" value="#{'大众'}"></property>
<property name="price" value="#{'120000'}"></property>
</bean>
SpEL还能引用其他bean的属性和方法:
<bean id="person" class="cn.itcast.spring3.demo5.Person">
<!--<property name="name" value="#{personInfo.name}"/>-->
<property name="name" value="#{personInfo.showName()}"/>
<property name="car2" value="#{car2}"/>
</bean>
<bean id="personInfo"class="cn.itcast.spring3.demo5.PersonInfo">
<property name="name" value="张三"/>
</bean>
Spring集成JUnit测试:
在测试类中直接使用注解加载配置文件、注入Service并进行测试,比之前简便许多。在开发中这种测试方式用的比较普遍。
1.程序中有Junit环境.
2.导入一个jar包.spring与junit整合jar包.
* spring-test-3.2.7.RELEASE.jar
3.测试代码:
- package com.js.Test;
- import org.junit.Test;
- import org.junit.runner.RunWith;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.test.context.ContextConfiguration;
- import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
- import com.js.demo1.UserService;
- /**
- * 引入了jar包之后,就可以使用一些注解了
- * @RunWith(SpringJUnit4ClassRunner.class)写法固定
- * @author hdb
- *
- */
- @RunWith(SpringJUnit4ClassRunner.class)
- @ContextConfiguration(locations="classpath:applicationContext.xml")
- public class SpringTest {
- @Autowired
- private UserService userService;
- @Test
- public void demo1(){
- userService.sayHello();
- }
- }
参考:https://blog.csdn.net/dove_knowledge/article/category/6818451/2
Spring IOC学习的更多相关文章
- Spring5 概述及Spring IOC学习
Spring Framework 5 1. Spring框架 1.1 Spring框架概述 1.2 主要内容 Spring框架是一个开源的JavaEE的应用程序 主要核心是 IOC(控制反转)和AOP ...
- Spring IOC及AOP学习总结
一.Spring IOC体系学习总结: Spring中有两个容器体系,一类是BeanFactory.还有一类是ApplicationContext.BeanFactory提供了基础的容器功能.Appl ...
- 菜鸟学习spring IOC有感
一.spring IOC思想引入 事实上对于刚開始学习的人来说,在学习IOC的时候确实有点困难,主要是掌握其思想方面存在一丢丢的障碍,可是假设可以跨过这个障碍,则可以高速掌握当中的思想了.单从字 ...
- Spring IOC核心源码学习
1. 初始化 大致单步跟了下Spring IOC的初始化过程,整个脉络很庞大,初始化的过程主要就是读取XML资源,并解析,最终注册到Bean Factory中: 在完成初始化的过程后,Bean们就在B ...
- 框架源码系列六:Spring源码学习之Spring IOC源码学习
Spring 源码学习过程: 一.搞明白IOC能做什么,是怎么做的 1. 搞明白IOC能做什么? IOC是用为用户创建.管理实例对象的.用户需要实例对象时只需要向IOC容器获取就行了,不用自己去创建 ...
- 【转】Spring学习---Spring IoC容器的核心原理
[原文] Spring的两个核心概念:IoC和AOP的雏形,Spring的历史变迁和如今的生态帝国. IoC和DI的基本概念 IoC(控制反转,英文含义:Inverse of Control)是Spr ...
- Spring框架学习之IOC(二)
Spring框架学习之IOC(二) 接着上一篇的内容,下面开始IOC基于注解装配相关的内容 在 classpath 中扫描组件 <context:component-scan> 特定组件包 ...
- Spring框架学习之IOC(一)
Spring框架学习之IOC(一) 先前粗浅地学过Spring框架,但当时忙于考试及后期实习未将其记录,于是趁着最近还有几天的空闲时间,将其稍微整理一下,以备后期查看. Spring相关知识 spri ...
- Spring IOC设计原理解析:本文乃学习整理参考而来
Spring IOC设计原理解析:本文乃学习整理参考而来 一. 什么是Ioc/DI? 二. Spring IOC体系结构 (1) BeanFactory (2) BeanDefinition 三. I ...
随机推荐
- SLG手游Java服务器的设计与开发——网络通信
文章版权归腾讯GAD所有,禁止匿名转载:禁止商业使用:禁止个人使用. 一.前言 上文分析了我们这款SLG的架构,本章着重讲解我们的网络通信架构,由上文的功能分析我们可以得知,游戏的所有功能基本上属于非 ...
- 【运维技术】Zookeeper单机以及集群搭建教程
Zookeeper单机以及集群搭建教程 单机搭建 单机安装以及启动 安装zookeeper的前提是必须有java环境 # 选择目录进行下载安装 cd /app # 下载zk,可以去官方网站下载,自己上 ...
- [one day one question] 有没有免费接收短信验证用于注册的软件或者平台?
问题描述: 想要批量注册撸羊毛,有手机短信验证码验证,这怎么破? 解决方案: 免费的肯定没有的,不过"一条短信收费一毛钱"倒是有一个,本人是亲自试用过,该平台收不到短信验证码不收费 ...
- MySQL事务之-2
在上一篇中我们提到了MySQL的事务特性,这一片主要讲述事务的实现. 事务的隔离性由锁来实现.原子性,一致性,持久性通过数据库的redo和undo log来实现. redo恢复提交事务修改页的操作,而 ...
- Java判断字符串是否符合yyyyMMdd日期格式
Java判断字符串是否符合yyyyMMdd日期格式 代码: /** * 判断参数的格式是否为“yyyyMMdd”格式的合法日期字符串 * */ public static boolean isVali ...
- InstallShieldpro2015 使用教程
1.下载地址:http://pan.baidu.com/s/1pLDCh3H ,如果网盘链接失效,请联系我. 2.解压后双击 3.安装完毕后,运行InstallShieldpro2015,会出现如下提 ...
- github上fork别人的代码之后,如何保持和原作者同步的更新
1.从自己fork之后的版本库clone $ git clone -o chucklu https://github.com/chucklu/Hearthstone-Deck-Tracker.git ...
- 【Java----统计字符串匹配个数】
org.apache.commons.lang3.StringUtils包带的工具类 StringUtils.countMatches(context, keyword);
- div框选中状态,倒三角样式
html代码: <html> <head> <style> #triangle-bottomright { width:0; height: 0; display: ...
- Qt5_vs2013_error_C2001: 常量中有换行符__资料
ZC: Win7x64 + Qt551(x86) + vs2013(x86) ZC: 问题:UTF-8 在源码文件中有中文时,有时会报编译错误:C2001 & C2143 分析: --> ...