Spring简单理解IOC和DI

来源:互联网 发布:做淘宝网店要实体店吗 编辑:程序博客网 时间:2024/05/18 09:18
**************IOC的控制反转
1.lazy-init="default"   当spring容器启动的时候lazy-init="default"的时候对象的初始化时在spring容器启动的时候进行的初始化
2.lazy-init="true"   这个的目的是在spring容器在启动的时候没有初始化,而是在context.getBean("helloWorld"),的时候进行的初始化,同时拿到这个对象
两者的区别:
1.第一种方式,在容器启动的时候进行的初始化,可以实时的检查出配置的文件是否正确
2.第二种方式是属于懒加载的方式,适用的场合是,在需要某个类的时候进行初始化
--
spring  init  destroy
init   在Spring容器启动的时候进行初始化
destroy 在Spring容器销毁的时候或者close()方法执行的时候调用的方法,但是Spring容器不会去destroy


**************DI(依赖注入),是指Spring给bean中注入属性值
--setter
spring中的setter属性的注入,依赖的是property来进行的注入
property中,name对应着bean中的属性,如果是基本类型的情况下,则使用的是value进行赋值,如果是引用类型的情况下,使用的是ref类型来进行属性的赋值
<property name="" value=""/>
<property name="" ref="" />
property中的name属性是lists的时候,
<property name ="lists">
<list>
<value>list1</value>
<value>list2</value>
<ref bean="student"> //这个的目的是在lists中放入的是student对象。
</list>
</property>
--scope在设置的时候,优先级低于依赖性。
--执行顺序,启动spring容器,实例化对象,实例化依赖,进行setter(装配属性)方法,进行init(),context.getBean();
--调用构造函数来赋值:
在构造器中进行赋值,在applicationContext.xml配置文件中进行配置构造器的参数:
index构造器中参数的下标:
<constructor-arg index="0" value="1" type="java.lang.lang" ref="student"></constructor-arg >
总结:可以灵活的使用构造器和setter方法进行属性赋值。
****************Spring特点是:
IOC和DI意义:
做到了完全的面向接口编程。



applicationContext.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-2.0.xsd"><alias name="helloWorld" alias="abc"/><bean id="helloWorld" class ="com.cn.HelloWorld"  lazy-init="true" scope = "singleton" init-method="" destroy-method=""></bean></beans>


HelloWorld.java

package com.cn;/** * 创建工厂的三种方式 * 1.采用默认的方式 * 2.采用静态工厂 * 3.采用实例工厂,多用在第三方的整合中,factory-bean   factory-methods * @author Administrator * */public class HelloWorld {public HelloWorld(){System.out.println("new instance..默认采用的是这种方式来创建的实例化对象...");}public void say(){System.out.println("HelloWorld...");}}







Junit测试类的包




Spring未整合的包