spring框架开发笔记 lesson1 IOC

Spring

IOC ( 控制反转 Inverse of Controller)

Spring中对象工厂(Spring容器):

  对象不能自己通过new 来创建,而是要通过Spring容器来创建(对象工厂),所以对象的创建的权利发生了反转,反转给容器创建.  A类和B类对象都交给容器创建,在A类中定义一个B类的属性,可以通过属性的set方法给属性赋值.

解耦合:对象由容器创建,管理,耦合关系解除


容器默认是通过反射来创建bean 对象:

Class c1 = Class.forName(全类名);

Class c2 = 类名.class

Class c3 = 对象.getClass();

框架底层创建对象原理 :反射动态创建对象

输入类名 创建对象

Scanner sca =  new Scanner (System.in)

String className =sca.next();

Class c = Class.forName(className);

Object obj = c. newInstance();


导入jar包

commons-logging-1.1.1.jar

org.springframework.asm-3.1.1.RELEASE.jar

org.springframework.beans-3.1.1.RELEASE.jar

org.springframework.context-3.1.1.RELEASE.jar

org.springframework.core-3.1.1.RELEASE.jar

org.springframework.expression-3.1.1.RELEASE.jar


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-3.1.xsd">

  

<!--将dao对象 和service对象交给容器统一创建

class :全类名,不能写接口

id: 唯一标识

lazy-init: 延迟创建对象 true 在调用方法时延迟创建 false 在创建容器时立即创建

scope: singleton: 单例的 只创建一个对象  prototype: 多例的,调用一个创建一个

                request: web 环境下 一次请求创建一个对象

                session: web 环境下 一次会话创建一个对象

init-method:   指定初始化方法(值为方法名)    容器创建时会调用

destroy-method: 容器销毁时创建

-->

<bean  class="dao.DeptDaoHibernateImpl" destroy-method="destroy"    init-method="init"  scope="singleton"  lazy-init="true"  id="deptDao">相当于new 了一个对象

</bean>

<bean class="dao.DeptDaoJDBCImpl" id="deptDao2">

</bean>

<bean class="dao.DeptDaoMybatisImpl" id="deptDao3">

</bean>

<bean class="service.DeptServiceImpl" id="deptService">

  <!-- name:属性名   ref : bean的id值

   底层会调用dao属性  set方法 

  -->

          <property name="dao" ref="dept"></property> 给属性赋值, 更换id值可以更换调用的dao

</beans>


测试

创建容器对象 加载applicationContext.xml ,创建bean对象*(调用的构造方法)

ApplicationContext ac  = new ClassPathXmlApplicationContext("applicationContext.xml"); 创建工厂耗时较多, 在框架整中通过监听器来创建

获取bean对象

IDeptService service = (IDeptService) ac .getBean("deptService");

service.saveDepte(new Dept()); // 调用Dao的方法


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值