spring IOC 模拟实现
IOC即inverse of control 控制反转
以前对象之间的引用是通过new来调用实现,有了Spring IOC,我们可以把对象之间的引用交给他来管理,这样就把控制权交给了Spring,所以就叫做控制反转。
Spring IOC的实现用到了设计模式:简单工厂,他也是从简单工厂进化而来的,下面我们看看Spring的IOC是如何进化来的。
简单工厂模式实现:
package org;
//抽象接口
interface Fruit{
public void eat();
}
//实现类A
class Apple implements Fruit{
public void eat(){
System.out.println("吃苹果。");
}
}
//实现类B
class Orange implements Fruit{
public void eat(){
System.out.println("吃橘子");
}
}
//工厂类
class Factory{
public static Fruit getInstance(String className){
Fruit f=null;
if(className.equals("apple")){
f=new Apple();
}
if(className.endsWith("orange")){
f=new Orange();
}
return f;
}
}
public class FactoryDemo02 {
public static void main(String args[]){
Fruit f=Factory.getInstance("apple");
f.eat();
}
}
package org;//抽象接口interface Fruit{public void eat();}//实现类Aclass Apple implements Fruit{public void eat(){System.out.println("吃苹果。");}}//实现类Bclass Orange implements Fruit{public void eat(){System.out.println("吃橘子");}}//工厂类class Factory{public static Fruit getInstance(String className){Fruit f=null;if(className.equals("apple")){f=new Apple();}if(className.endsWith("orange")){f=new Orange();}return f;}}public class FactoryDemo02 {public static void main(String args[]){Fruit f=Factory.getInstance("apple");f.eat();}}
反射+简单工厂
但是工厂类如果这样写的话,就有一个问题,如果增加了水果,比如香蕉,那么在工厂类里面也要进行相关的修改了,这样不合理,而java的反射机制可以解决这个问题
package org1;interface Fruit {public void eat();}class Apple implements Fruit {public void eat() {System.out.println("吃苹果。");}}class Orange implements Fruit {public void eat() {System.out.println("吃橘子");}}class Factory {public static Fruit getInstance(String className) {Fruit f = null;try {f = (Fruit) Class.forName(className).newInstance();} catch (Exception e) {e.printStackTrace();}return f;}}public class CopyOfFactoryDemo03 {public static void main(String args[]) {Fruit f = Factory.getInstance("org1.Apple");f.eat();}}
package org3;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.util.Properties;interface Fruit {public void eat();}class Apple implements Fruit {public void eat() {System.out.println("吃苹果。");}}class Orange implements Fruit {public void eat() {System.out.println("吃橘子");}}class Factory {public static Fruit getInstance(String className) {Fruit f = null;try {f = (Fruit) Class.forName(className).newInstance();} catch (Exception e) {e.printStackTrace();}return f;}}class PropertiesOperate{private Properties pro=null;private File file=new File("d:"+File.separator+"fruit.properties");public PropertiesOperate(){this.pro=new Properties();if(file.exists()){try {pro.loadFromXML(new FileInputStream(file));} catch (Exception e) {e.printStackTrace();}}else{this.save();}}private void save(){this.pro.setProperty("apple","org3.Apple");this.pro.setProperty("orange", "org3.Orange");try {this.pro.storeToXML(new FileOutputStream(this.file),"Fruit");} catch (Exception e) {e.printStackTrace();}}public Properties getProperties(){return this.pro;}}public class CopyOfFactoryDemo04 {public static void main(String args[]) {Properties pro=new PropertiesOperate().getProperties();Fruit f= Factory.getInstance(pro.getProperty("apple"));f.eat();}}
package test2;public class Person {private String name;private int age;private Grade grade;public String getName() {return name;}public Grade getGrade() {return grade;}public void setGrade(Grade grade) {this.grade = grade;}public void setName(String name) {this.name = name;}public void setAge(int age) {this.age = age;}public int getAge() {return age;}public int getTotleGrade() {return grade.getEnglish()+grade.getMath();}}
package test2;public class Grade {private int math;private int english;public int getMath() {return math;}public void setMath(int math) {this.math = math;}public int getEnglish() {return english;}public void setEnglish(int english) {this.english = english;}}
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN""http://www.springframework.org/dtd/spring-beans.dtd"><beans>//很多豆豆<bean id="Person" class="test2.Person">//第一个豆豆,是一个Person类,id名字随便取,还要写上类的全名<property name="name">//下面开始把这个类里面的所有属性列出来,并赋值,至于你说难道一定要赋值吗?我想可以,我刚学,不知道<value>小龙</value>//这里的名字是通过程序里面的set来赋值的,不信你去掉程序里面相关的set,就出错了</property><property name="age"><value>23</value></property><property name="grade">//这里有点特别,这个grade变量是一个对象,和一般的变量要区别对待<ref local="Grade"/>//这里指向了本配置文件里面一个名字叫Grade(即id=Grade)的bean</property></bean><bean id="Grade" class="test2.Grade">//同上<property name="math"><value>99</value></property><property name="english"><value>59</value></property></bean></beans>
package test2;import org.springframework.beans.factory.BeanFactory;import org.springframework.beans.factory.xml.XmlBeanFactory;import org.springframework.core.io.ClassPathResource;import org.springframework.core.io.Resource;import test.ExampleBean;public class Test {public static void main(String args[]){Resource input = new ClassPathResource("test2/Bean.xml");//Bean.xml的路径System.out.println("resource is:" + input);BeanFactory factory = new XmlBeanFactory(input);//把input扔到工厂里面去,这个工厂就能为你提供实例了(我也不知道能不能这样说)Person person =(Person) factory.getBean("Person");//你要一个叫Person的东西,那好,工厂就去找“Person"给你Grade grade=(Grade)factory.getBean("Grade");System.out.println("姓名:"+person.getName());//person可以调用里面相关的方法,就相当于new了一个Person一样System.out.println("年龄:"+person.getAge());System.out.println("数学成绩:"+grade.getMath());System.out.println("英语成绩:"+grade.getEnglish());System.out.println("数学,英语总成绩:"+person.getTotleGrade());}}
FileSystemResource --- 从文件系统加载,比如说自己指定配置文件的全路径
InputStreamResource --- 从输入流中加载
ServletContextResource --- 从Servlet 上下文环境中加载
UrlResource --- 从指定的Url加载
• MessageSource, 提供国际化的消息访问
• 资源访问,如URL和文件
• 事件传播
• 载入多个(有继承关系)上下文 ,使得每一个上下文都专注于一个特定的层次,比如应用的web层
spring IOC 模拟实现的更多相关文章
- 手动模拟实现Spring IOC功能(基于javaConfig风格)
以下文中spring特指spring frameWork项目,不含其它:如spring cloud等. 作为刚开始研究spring源码的小白,对于spring两大核心功能之一的IOC,虽说大致了解了B ...
- (反射+内省机制的运用)简单模拟spring IoC容器的操作
简单模拟spring IoC容器的操作[管理对象的创建.管理对象的依赖关系,例如属性设置] 实体类Hello package com.shan.hello; public class Hello { ...
- spring ioc aop 原理
spring ioc aop 原理 spring ioc aop 的原理 spring的IoC容器是spring的核心,spring AOP是spring框架的重要组成部分. 在传统的程序设计中,当调 ...
- J2EE进阶(十四)超详细的Java后台开发面试题之Spring IOC与AOP
J2EE进阶(十四)超详细的Java后台开发面试题之Spring IOC与AOP 前言 搜狐畅游笔试题中有一道问答题涉及到回答谈谈对Spring IOC与AOP的理解.特将相关内容进行整理. ...
- Spring IOC(三)依赖注入
本系列目录: Spring IOC(一)概览 Spring IOC(二)容器初始化 Spring IOC(三)依赖注入 Spring IOC(四)总结 目录 1.AbstractBeanFactory ...
- Spring IOC容器基本原理
2.2.1 IOC容器的概念IOC容器就是具有依赖注入功能的容器,IOC容器负责实例化.定位.配置应用程序中的对象及建立这些对象间的依赖.应用程序无需直接在代码中new相关的对象,应用程序由IOC容器 ...
- Spring IOC(一)概览
Spring ioc源码解析这一系列文章会比较枯燥,但是只要坚持下去,总会有收获,一回生二回熟,没有第一次,哪有下一次... 本系列目录: Spring IOC(一)概览 Spring IOC(二)容 ...
- springmvc 运行原理 Spring ioc的实现原理 Mybatis工作流程 spring AOP实现原理
SpringMVC的工作原理图: SpringMVC流程 . 用户发送请求至前端控制器DispatcherServlet. . DispatcherServlet收到请求调用HandlerMappin ...
- spring IOC的实现原理
姓名:陈中娇 班级:软件151 1. IOC容器就是具有依赖注入功能的容器,IOC容器负责实例化.定位.配置应用程序中的对象及建立这些对象间的依赖.应用程序无需直接在代码中new相关的对象,应 ...
随机推荐
- excel中的数据粘贴不全到plsql中,excel 粘贴后空白,Excel复制粘贴内容不全
http://zhidao.baidu.com/link?url=pHZQvfWJzI-lQjl4uP86q4GLcpYHu4o-fdjiYegJS0Cy5HEq5oz0YrUye3iHjmv5CJ3 ...
- resume.c
resume.c //采用CURLOPT_RESUME_FROM_LARGE 实现文件断点续传功能 #include <stdlib.h> #include <stdio.h> ...
- 一张图告诉你:Android系统哪代强?
一张图告诉你:Android系统哪代强? 新浪科技 王上 谷歌发布Android 1.5 的时候,开始以甜点命名,作为每个版本代表的甜点的尺寸越变越大.谷歌在2014年10月中旬发布了Android ...
- MySQL-慢查询日志
慢查询日志功能默认不开启,其记录了执行时间超过参数long_query_time的值(默认是10),且访问的行数超过了参数min_examined_row_limit的值得SQL语句. mysql&g ...
- appium简明教程(1)——appium和它的哲学世界
什么是appium? 本文已经迁移到测试教程网,后续更新会在测试教程网更新. 下面这段介绍来自于appium的官网. Appium is an open-source tool you can use ...
- Maven for Eclipse 第三章 ——创建和导入 Maven 项目
这一章主要介绍 Maven 项目的结构,它的构建的架构,主要涵盖了必需的主题,最后将学习如何创建一个简单的 Maven 项目.这章主要包括以下部分. Maven 项目的结构 POM 文件(Projec ...
- 关于 f 散度
在概率统计中,f散度是一个函数,这个函数用来衡量两个概率密度p和q的区别,也就是衡量这两个分布多么的相同或者不同. 1.f散度的定义p和q是同一个空间中的两个概率密度函数,它们之间的f散度可以用如下方 ...
- [转]java调用外部程序Runtime.getRuntime().exec
Runtime.getRuntime().exec()方法主要用于执行外部的程序或命令. Runtime.getRuntime().exec共有六个重载方法: public Process exec( ...
- Java 8 – TemporalAdjusters examples
1. TemporalAdjusters Example to move a date to firstDayOfMonth, firstDayOfNextMonth, next Monday and ...
- centos7 中搭建gitlab
1.在virtual box中新建一个虚拟机 2.gitlab ce(community版本)地址:https://about.gitlab.com/installation/#centos-7?ve ...