spring学习笔记1

来源:互联网 发布:egd网络黄金 编辑:程序博客网 时间:2024/05/29 05:53

         spring简介 

       spring是一个优秀的框架,它的核心是控制反转和依赖注入。所谓控制反转是指,应用本身不负责依赖对象的创建及维护,依赖对象的创建和维护是由外部容器负责的,控制权的转移就是控制反转;依赖注入是指,由外部容器动态的将依赖对象注入到组件中。

      优点:①降低组件之间的耦合度,实现软件各层之间的解耦。

                  ②使用容器为其提供众多服务,事务管理服务(开启和关闭事务)、JMS服务、持久化服务、spring core 核心服务等。

                  ③容器提供单例模式的支持,开发人员不在需要自己编写实现代码。

                  ④容器提供AOP技术,利用他容易实现权限拦截等功能。

                  ⑤提供辅助类,JDBCtemplate, HibernateTemplate,能加快应用的开发。

                  ⑥对于主流框架提供了集成支持。

        界定一个框架是轻或者重的框架,是看使用它时,它开启的服务的多少来决定的。

         spring开发环境的搭建

      使用spring所需要的包:
      

            spring的配置文件模板。
<?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.5.xsd">
          <bean id="personService" class="cn.itcast.service.impl.PersonServiceBean"></bean></beans>
 配置好bean之后,该bean就被spring容器管理。            

 实例化容器

   
    调用
    PersonService  p= ( PersonService) ctx.getBean("personService");
    p.save();  
    

spring实例化bean的三种方式:


一、使用构造器实例化;

  1. <!--applicationContext.xml配置:-->  
  2.   
  3. <bean id="personService" class="cn.mytest.service.impl.PersonServiceBean"></bean>

二、使用静态工厂方法实例化;

  1. public void instanceSpring(){  
  2.                 //加载spring配置文件  
  3.         ApplicationContext ac = new ClassPathXmlApplicationContext(  
  4.                 new String[]{  
  5.                         "/conf/applicationContext.xml"  
  6.                 });  
  7.         //调用getBean方法取得被实例化的对象。  
  8.         PersonServiceBean psb = (PersonServiceBean) ac.getBean("personService");  
  9.           
  10.         psb.save();  
  11. }  

三、使用实例化工厂方法实例化。

  1. package cn.mytest.service.impl;  
  2.   
  3. /** 
  4. *创建工厂类 
  5. * 
  6. */  
  7. public class PersonServiceFactory {  
  8.     //创建静态方法  
  9.     public static PersonServiceBean createPersonServiceBean(){  
  10.          //返回实例化的类的对象  
  11.         return new PersonServiceBean();  
  12.     }  
  13. }  
xml代码

  1. <!--applicationContext.xml配置:-->  
  2.   
  3. <bean id="personService1" class="cn.mytest.service.impl.PersonServiceFactory" factory-method="createPersonServiceBean"></bean> 
java代码

  1. public void instanceSpring(){  
  2.                 //加载spring配置文件  
  3.         ApplicationContext ac = new ClassPathXmlApplicationContext(  
  4.                 new String[]{  
  5.                         "/conf/applicationContext.xml"  
  6.                 });  
  7.         //调用getBean方法取得被实例化的对象。  
  8.         PersonServiceBean psb = (PersonServiceBean) ac.getBean("personService1");  
  9.           
  10.         psb.save();  
  11. }  








       
0 0