3.spring IOC、DI 介绍

来源:互联网 发布:深圳云计算招聘岗位 编辑:程序博客网 时间:2024/06/06 18:57

一.IOC(Inversion[倒置、转化] of Control)控制反转

使一个对象依赖的其他对象通过被动的方式传递进来,而不是对象自己创建或查找依赖对象。
是容器主动将资源传递给它所管理的对象,对象(组建)所需要做的选择一种合适的方式来接收资源

二.DI(Dependency[属地、从属] Injection[注射、注射剂])依赖注入

是IOC的另一种表述方式
就是对象(组建)可以预先定义好的方式(setter[安放者,安装员]和构造方法)来接收来自容器的资源注入

三.spring IOC容器实现的两种方式:

(1)BeanFactory:IOC容器的基本实现

(2)ApplicationContext:它是BeanFactory的子接口,提供了更多的高级特性

--ClassPathXmlApplicationContext:从类的路径下加载配置文件

--ConfigurableAppcationContext:ApplicationContext的子接口

(有ConfigurableAppcationContext bf=null;

提供bf.refresh()//刷新:bf.close()//关闭 

方法)


Bean的作用域

默认情况下,spring容器里的bean只创建唯一一个实例,默认为:scope="singleton"  [scope范围,眼界,见识]

singleton:一个对象在spring IOC容器中只有一个bean的实例,以单个实例的方式存在(单例模式)

prototype:每次调用getBean()时候,都会创建一个新的实例

request:每次Http请求的时候创建一个新的Bean,用于WebApplicationContext

session:在同一HTTPSession中共享一个Bean,用于WebApplicationContext


实例1:scope="singleton"

1.结构目录:


2.代码

UserInfo.java

package com;public class UserInfo {private Integer userId;private String userName;public void setUserId(Integer userId) {this.userId = userId;}public void setUserName(String userName) {this.userName = userName;}public void getUserName() {System.out.println("姓名1:"+userName);}@Overridepublic String toString() {return "UserInfo [userId=" + userId + ", userName=" + userName + "]";}}


Test.java

package test;import org.springframework.beans.factory.BeanFactory;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.UserInfo;public class Test {public static void main(String[] args) {BeanFactory bf=new ClassPathXmlApplicationContext("beans.xml");UserInfo user=(UserInfo)bf.getBean("userInfo");UserInfo user1=(UserInfo)bf.getBean("userInfo");System.out.println(user==user1);//tureuser.getUserName();//姓名1:悟空user1.getUserName();//姓名1;悟空}}


singleton:一个对象在spring IOC容器中只有一个bean的实例,以单个实例的方式存在(单例模式)
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"    xsi:schemaLocation="http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"><!-- UserInfo的bean --><!--UserInfo userInfo=new UserInfo(); userInfo.setUserName("悟空");-->   <bean id="userInfo" class="com.UserInfo" scope="singleton">       <property name="userId" value="001"/>       <property name="userName" value="悟空"/>    </bean></beans>


打印结果:



实例2:scope="prototype"

prototype:每次调用getBean()时候,都会创建一个新的实例

beans.xml


打印结果:



原创粉丝点击