Spring ioc Di概念

本文详细解释了Java程序中通过Spring容器实现控制反转(IoC)和依赖注入(DI)的概念,阐述了传统对象耦合与IoC思想的区别,并提供了Spring配置和简单实例,帮助开发者掌握如何利用Spring简化对象依赖关系。

Ioc:

java程序中的每个业务逻辑至少需要两个或以上的对象来协作完成,通常,每个对象在使用他的合作对象时,自己均要使用像new object()

这样的语法来完成合作对象的申请工作。你会发现:对象间的耦合度高了。

而IOC的思想是:Spring容器来实现这些相互依赖对象的创建、协调工作。对象只需要关系业务逻辑本

身就可以了。从这方面来说,对象如何得到他的协作对象的责任被反转了(IOC、DI)

IoC与DI

  首先想说说IoC(Inversion of Control,控制倒转)。这是spring的核心,贯穿始终。所谓IoC,对于spring框架来说,就是由spring来负责控制对象的生命周期和对象间的关系。这是什么意思呢,举个简单的例子,我们是如何找女朋友的?常见的情况是,我们到处去看哪里有长得漂亮身材又好的mm,然后打听她们的兴趣爱好、qq号、电话号、ip号、iq号………,想办法认识她们,投其所好送其所要,然后嘿嘿……这个过程是复杂深奥的,我们必须自己设计和面对每个环节。传统的程序开发也是如此,在一个对象中,如果要使用另外的对象,就必须得到它(自己new一个,或者从JNDI中查询一个),使用完之后还要将对象销毁(比如Connection等),对象始终会和其他的接口或类藕合起来。

  那么IoC是如何做的呢?有点像通过婚介找女朋友,在我和女朋友之间引入了一个第三者:婚姻介绍所。婚介管理了很多男男女女的资料,我可以向婚介提出一个列表,告诉它我想找个什么样的女朋友,比如长得像李嘉欣,身材像林熙雷,唱歌像周杰伦,速度像卡洛斯,技术像齐达内之类的,然后婚介就会按照我们的要求,提供一个mm,我们只需要去和她谈恋爱、结婚就行了。简单明了,如果婚介给我们的人选不符合要求,我们就会抛出异常。整个过程不再由我自己控制,而是有婚介这样一个类似容器的机构来控制。Spring所倡导的开发方式就是如此,所有的类都会在spring容器中登记,告诉spring你是个什么东西,你需要什么东西,然后spring会在系统运行到适当的时候,把你要的东西主动给你,同时也把你交给其他需要你的东西。所有的类的创建、销毁都由spring来控制,也就是说控制对象生存周期的不再是引用它的对象,而是spring。对于某个具体的对象而言,以前是它控制其他对象,现在是所有对象都被spring控制,所以这叫控制反转。如果你还不明白的话,我决定放弃。

IoC的一个重点是在系统运行中,动态的向某个对象提供它所需要的其他对象。这一点是通过DI(Dependency Injection,依赖注入)来实现的。比如对象A需要操作数据库,以前我们总是要在A中自己编写代码来获得一个Connection对象,有了spring我们就只需要告诉spring,A中需要一个Connection,至于这个Connection怎么构造,何时构造,A不需要知道。在系统运行时,spring会在适当的时候制造一个Connection,然后像打针一样,注射到A当中,这样就完成了对各个对象之间关系的控制。A需要依赖Connection才能正常运行,而这个Connection是由spring注入到A中的,依赖注入的名字就这么来的。那么DI是如何实现的呢?Java 1.3之后一个重要特征是反射(reflection),它允许程序在运行的时候动态的生成对象、执行对象的方法、改变对象的属性,spring就是通过反射来实现注入的。关于反射的相关资料请查阅java doc。


spring简单实例:

people类属性:(String)uname,(Shopping)sp;

Shopping类:(String)spName

这是一个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"
     xmlns:context="http://www.springframework.org/schema/context"
     xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/context
         http://www.sprinsgframework.org/schema/context/spring-context-3.0.xsd">
           

<bean id="t_people" scope="singleton" class="org.ymm.entity.People" >
	<!--将bean id为t_sp的注入到这个bean中   sp是Shopping类在People中的属性  -->
	<property name="sp">
		<ref bean="t_sp"/>
	</property>
	<property name="uname">
		<value>张三</value>
	</property>
</bean>

<bean id="t_sp" class="org.ymm.entity.Shopping" init-method="init_xxaa">
	<property name="spName">
		<value>脑残方便面</value>
	</property>
</bean>
</beans>


注:init-method属性指定某个方法 这个方法在初始化(shopping)对象后执行


测试

package org.ymm.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.ymm.entity.People;

public class Test {
	public static void main(String[] args) {
		ApplicationContext con= new ClassPathXmlApplicationContext("tx.xml");
		People p= con.getBean("t_people", People.class);
		p.setUname("xxmm");
		System.out.println(p.getUname()+"购买了"+p.getSp().getSpName());
		/*
		 * tx.xml中bean的scope属性给 prototype 是实例化一个新的对象
		 * tx.xml中bean的scope属性给 singleton 是都用相同的那个对象
		 **/
		People p2= con.getBean("t_people", People.class);
		System.out.println(p2.getUname()+"购买了"+p2.getSp().getSpName());
	}
}

注:scope属性singleton和prototype;



一个Bean包括id,type,和Properties。

new ClassPathXmlApplicationContext开始加载我们的配置文件了,将我们配置的信息保存在一个HashMap中,HashMap的key就是Bean 的 Id ,HasMap 的value是这个Bean,只有这样我们才能通过context.getBean("animal")这个方法获得Animal这个类。我们都知道Spirng可以注入基本类型,而且可以注入像List,Map这样的类型,接下来就让我们以Map为例看看Spring是怎么保存的吧

Map配置可以像下面的

Java代码
  1. <beanid="test"class="Test">
  2. <propertyname="testMap">
  3. <map>
  4. <entrykey="a">
  5. <value>1</value>
  6. </entry>
  7. <entrykey="b">
  8. <value>2</value>
  9. </entry>
  10. </map>
  11. </property>
  12. </bean>
[java] view plain copy
  1. <beanid="test"class="Test">
  2. <propertyname="testMap">
  3. <map>
  4. <entrykey="a">
  5. <value>1</value>
  6. </entry>
  7. <entrykey="b">
  8. <value>2</value>
  9. </entry>
  10. </map>
  11. </property>
  12. </bean>


Spring是怎样保存上面的配置呢?,代码如下:

Java代码
  1. if(beanProperty.element("map")!=null){
  2. Map<String,Object>propertiesMap=newHashMap<String,Object>();
  3. ElementpropertiesListMap=(Element)beanProperty
  4. .elements().get(0);
  5. Iterator<?>propertiesIterator=propertiesListMap
  6. .elements().iterator();
  7. while(propertiesIterator.hasNext()){
  8. Elementvet=(Element)propertiesIterator.next();
  9. if(vet.getName().equals("entry")){
  10. Stringkey=vet.attributeValue("key");
  11. Iterator<?>valuesIterator=vet.elements()
  12. .iterator();
  13. while(valuesIterator.hasNext()){
  14. Elementvalue=(Element)valuesIterator.next();
  15. if(value.getName().equals("value")){
  16. propertiesMap.put(key,value.getText());
  17. }
  18. if(value.getName().equals("ref")){
  19. propertiesMap.put(key,newString[]{value
  20. .attributeValue("bean")});
  21. }
  22. }
  23. }
  24. }
  25. bean.getProperties().put(name,propertiesMap);
  26. }
[java] view plain copy
  1. if(beanProperty.element("map")!=null){
  2. Map<String,Object>propertiesMap=newHashMap<String,Object>();
  3. ElementpropertiesListMap=(Element)beanProperty
  4. .elements().get(0);
  5. Iterator<?>propertiesIterator=propertiesListMap
  6. .elements().iterator();
  7. while(propertiesIterator.hasNext()){
  8. Elementvet=(Element)propertiesIterator.next();
  9. if(vet.getName().equals("entry")){
  10. Stringkey=vet.attributeValue("key");
  11. Iterator<?>valuesIterator=vet.elements()
  12. .iterator();
  13. while(valuesIterator.hasNext()){
  14. Elementvalue=(Element)valuesIterator.next();
  15. if(value.getName().equals("value")){
  16. propertiesMap.put(key,value.getText());
  17. }
  18. if(value.getName().equals("ref")){
  19. propertiesMap.put(key,newString[]{value
  20. .attributeValue("bean")});
  21. }
  22. }
  23. }
  24. }
  25. bean.getProperties().put(name,propertiesMap);
  26. }



接下来就进入最核心部分了,让我们看看Spring 到底是怎么依赖注入的吧,其实依赖注入的思想也很简单,它是通过反射机制实现的,在实例化一个类时,它通过反射调用类中set方法将事先保存在HashMap中的类属性注入到类中。让我们看看具体它是怎么做的吧。
首先实例化一个类,像这样

Java代码
  1. publicstaticObjectnewInstance(StringclassName){
  2. Class<?>cls=null;
  3. Objectobj=null;
  4. try{
  5. cls=Class.forName(className);
  6. obj=cls.newInstance();
  7. }catch(ClassNotFoundExceptione){
  8. thrownewRuntimeException(e);
  9. }catch(InstantiationExceptione){
  10. thrownewRuntimeException(e);
  11. }catch(IllegalAccessExceptione){
  12. thrownewRuntimeException(e);
  13. }
  14. returnobj;
  15. }
[java] view plain copy
  1. publicstaticObjectnewInstance(StringclassName){
  2. Class<?>cls=null;
  3. Objectobj=null;
  4. try{
  5. cls=Class.forName(className);
  6. obj=cls.newInstance();
  7. }catch(ClassNotFoundExceptione){
  8. thrownewRuntimeException(e);
  9. }catch(InstantiationExceptione){
  10. thrownewRuntimeException(e);
  11. }catch(IllegalAccessExceptione){
  12. thrownewRuntimeException(e);
  13. }
  14. returnobj;
  15. }


接着它将这个类的依赖注入进去,像这样

Java代码
  1. publicstaticvoidsetProperty(Objectobj,Stringname,Stringvalue){
  2. Class<?extendsObject>clazz=obj.getClass();
  3. try{
  4. StringmethodName=returnSetMthodName(name);
  5. Method[]ms=clazz.getMethods();
  6. for(Methodm:ms){
  7. if(m.getName().equals(methodName)){
  8. if(m.getParameterTypes().length==1){
  9. Class<?>clazzParameterType=m.getParameterTypes()[0];
  10. setFieldValue(clazzParameterType.getName(),value,m,
  11. obj);
  12. break;
  13. }
  14. }
  15. }
  16. }catch(SecurityExceptione){
  17. thrownewRuntimeException(e);
  18. }catch(IllegalArgumentExceptione){
  19. thrownewRuntimeException(e);
  20. }catch(IllegalAccessExceptione){
  21. thrownewRuntimeException(e);
  22. }catch(InvocationTargetExceptione){
  23. thrownewRuntimeException(e);
  24. }
  25. }
[java] view plain copy
  1. publicstaticvoidsetProperty(Objectobj,Stringname,Stringvalue){
  2. Class<?extendsObject>clazz=obj.getClass();
  3. try{
  4. StringmethodName=returnSetMthodName(name);
  5. Method[]ms=clazz.getMethods();
  6. for(Methodm:ms){
  7. if(m.getName().equals(methodName)){
  8. if(m.getParameterTypes().length==1){
  9. Class<?>clazzParameterType=m.getParameterTypes()[0];
  10. setFieldValue(clazzParameterType.getName(),value,m,
  11. obj);
  12. break;
  13. }
  14. }
  15. }
  16. }catch(SecurityExceptione){
  17. thrownewRuntimeException(e);
  18. }catch(IllegalArgumentExceptione){
  19. thrownewRuntimeException(e);
  20. }catch(IllegalAccessExceptione){
  21. thrownewRuntimeException(e);
  22. }catch(InvocationTargetExceptione){
  23. thrownewRuntimeException(e);
  24. }
  25. }


最后它将这个类的实例返回给我们,我们就可以用了。我们还是以Map为例看看它是怎么做的,我写的代码里面是创建一个HashMap并把该HashMap注入到需要注入的类中,像这样,

Java代码
  1. if(valueinstanceofMap){
  2. Iterator<?>entryIterator=((Map<?,?>)value).entrySet()
  3. .iterator();
  4. Map<String,Object>map=newHashMap<String,Object>();
  5. while(entryIterator.hasNext()){
  6. Entry<?,?>entryMap=(Entry<?,?>)entryIterator.next();
  7. if(entryMap.getValue()instanceofString[]){
  8. map.put((String)entryMap.getKey(),
  9. getBean(((String[])entryMap.getValue())[0]));
  10. }
  11. }
  12. BeanProcesser.setProperty(obj,property,map);
  13. }
[java] view plain copy
  1. if(valueinstanceofMap){
  2. Iterator<?>entryIterator=((Map<?,?>)value).entrySet()
  3. .iterator();
  4. Map<String,Object>map=newHashMap<String,Object>();
  5. while(entryIterator.hasNext()){
  6. Entry<?,?>entryMap=(Entry<?,?>)entryIterator.next();
  7. if(entryMap.getValue()instanceofString[]){
  8. map.put((String)entryMap.getKey(),
  9. getBean(((String[])entryMap.getValue())[0]));
  10. }
  11. }
  12. BeanProcesser.setProperty(obj,property,map);
  13. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值