【第22期】观点:IT 行业加班,到底有没有价值?

什么是IOC(DI),有什么好处(java project 的spring IOC模拟)

原创 2011年01月07日 23:03:00

IOCInversion Of Control,控制反转):一个类的某个属性需要使用时,需要有本类自己初始化。而在spring类的某些属性不用自己初始化而交给了spring来管理。这样的转换就是IOC思想。SpringIOC思想是,springIOC容器在初始化的时候就根据配置对相应的对象进行初始化,并放在容器中。同时根据配置对相应类的属性进行初始化。也就是DIDependency Injection依赖注入),至此类的初始化不需要类本身负责初始化而交给了spring容器。

IOC的好处是:降低耦合性:某个类的一个属性,以前是该类自己控制,而引人Spring后,这个类的属性由Spring控制。

Spring IOC的模拟所做的事情是:在xml文件配置好相应的bean,设置注入关系。在解析xml时候对bean进行初始化同时对相应属性进行注入。

//bean工厂接口

BeanFactory.java:

package com.xie.spring;

 

public interface BeanFactory {

    public Object getBean(String name);

}

//bean工厂的实现

ClassPathXmlApplicationContext.java

 

package com.xie.spring;

 

import java.io.IOException;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

 

import org.jdom.Document;

import org.jdom.Element;

import org.jdom.JDOMException;

import org.jdom.input.SAXBuilder;

 

public class ClassPathXmlApplicationContext implements BeanFactory{

        

         private Map<String,Object> beans=new HashMap<String, Object>();

        

        

 

         public ClassPathXmlApplicationContext() throws JDOMException, IOException, InstantiationException, IllegalAccessException, ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {

                   SAXBuilder sb=new SAXBuilder();

                   //Document doc=sb.build("src/beans.xml");

                   Document doc=sb.build(this.getClass().getClassLoader().getResourceAsStream("beans.xml"));

                   Element root=doc.getRootElement();

                   List<Element> lists=(List<Element>)root.getChildren("bean");

                   for (int i = 0; i <lists.size(); i++) {

                            Element ele=lists.get(i);

                            String id=ele.getAttributeValue("id");

                            String clazz=ele.getAttributeValue("class");

                            System.out.println(id+":"+clazz);

                            Object o=Class.forName(clazz).newInstance();

                            beans.put(id, o);

                            for (Element e:(List<Element>)ele.getChildren("property")) {

                                     String name=e.getAttributeValue("name");

                                String bean=e.getAttributeValue("bean");

                                     Object beanObject=beans.get(bean);

                                     String methodName="set"+name.substring(0, 1).toUpperCase()+name.substring(1);

                                     System.out.println("methodName=:"+methodName);

                                     Method m=o.getClass().getMethod(methodName, beanObject.getClass().getInterfaces()[0]);

                                m.invoke(o, beanObject);

                            }

                   }

 

                  

                  

         }

         @Override

         public Object getBean(String name) {

           return beans.get(name);

         }

        

}

//存储对象的实体类

User.java

package com.xie.spring.modal;

 

public class User {

    private String userName;

    private String passWord;

    public String getUserName() {

       return userName;

    }

    public void setUserName(String userName) {

       this.userName = userName;

    }

    public String getPassWord() {

       return passWord;

    }

    public void setPassWord(String passWord) {

       this.passWord = passWord;

    }

      

}

//dao抽象层

UserDAO.java

package com.xie.spring.dao;

 

import com.xie.spring.modal.User;

 

public interface UserDAO {

     public void save(User u);

}

package com.xie.spring.dao;

 

import com.xie.spring.modal.User;

//dao实现层

UserDAOImpl.java

public class UserDAOImpl implements UserDAO {

 

    @Override

    public void save(User u) {

       System.out.println("A user saved !");

    }

 

}

//service接口层

UserService.java

package com.xie.spring.service;

 

import com.xie.spring.modal.User;

 

public interface UserService {

       public void add(User u);

}

//service实现层

UserServiceImpl.java

package com.xie.spring.service;

 

import com.xie.spring.dao.UserDAOImpl;

import com.xie.spring.dao.UserDAO;

import com.xie.spring.modal.User;

 

public class UserServiceImpl implements UserService {

 

   private UserDAO userDao;

  

   public UserDAO getUserDao() {

            return userDao;

     }

 

   public void setUserDao(UserDAO userDao) {

            this.userDao = userDao;

     }

 

    public void add(User u) {

        this.userDao.save(u);

    }

}

//实现类

UserServiceTest.java

package com.xie.spring.service;

 

import static org.junit.Assert.*;

 

import java.io.IOException;

import java.lang.reflect.InvocationTargetException;

 

import org.jdom.JDOMException;

import org.junit.AfterClass;

import org.junit.BeforeClass;

import org.junit.Test;

 

import com.xie.spring.BeanFactory;

import com.xie.spring.ClassPathXmlApplicationContext;

import com.xie.spring.dao.UserDAOImpl;

import com.xie.spring.modal.User;

 

public class UserServiceTest {

 

         @BeforeClass

         public static void setUpBeforeClass() throws Exception {

         }

 

         @AfterClass

         public static void tearDownAfterClass() throws Exception {

         }

 

         @Test

         public void testAdd() throws JDOMException, IOException, InstantiationException, IllegalAccessException, ClassNotFoundException, SecurityException, IllegalArgumentException, NoSuchMethodException, InvocationTargetException {

                   //fail("Not yet implemented");

                   BeanFactory bf=new ClassPathXmlApplicationContext();

                   //UserService us=new UserService();

        UserServiceImpl us=(UserServiceImpl) bf.getBean("us");

                   //UserDAO userDAO=(UserDAO) bf.getBean("u");

                   //us.setUserDao(userDAO);

                   User u=new User();

                   us.add(u);

         }

}

版权声明:本文为博主原创文章,未经博主允许不得转载。 举报

相关文章推荐

模拟Spring的 IOC 和 DI

[size=xx-large][color=orange][b]模拟Spring的 IOC 和 DI[/b][/color][/size] [size=medium][color=red][b]1.BeanFactory 接口[/b][/color][/size] [code="jav...

《Spring3.X企业应用开发实战》学习笔记--IoC和AOP

本篇是“《Spring3.X企业应用开发实战》,陈雄华 林开雄著,电子工业出版社,2012.2出版”的学习笔记。 在日常的开发中,最近几年正在使用着Spring,过去几年中,使用过Spring.Ne...

程序员升职加薪指南!还缺一个“证”!

CSDN出品,立即查看!

SSH配置

本人ssh框架的版本是:struts2.2.3,hibernate3.1.2,spring3.0.6 下载地址: Struts:http://struts.apache.org/download.cgi hibernate:http://www.hiberna

Spring-IOC/DI-1

一 Spring基础 Eclipse安装 安装过程 导入jar包 Spring HelloWorld程序 1 HelloWorld类 2 不使用Spring的测试代码 3 配置xml文件 4 使用Sp...

JAVA三大框架SSH和MVC

Java—SSH(MVC) JAVA三大框架的各自作用   hibernate是底层基于jdbc的orm(对象关系映射)持久化框架,即:表与类的映射,字段与属性的映射,记录与对象的映射 数据库模型 也就是Model; struts提供的丰富标签是用于显示层View;同时struts也...
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)