zoukankan      html  css  js  c++  java
  • spring学习1

    一、spring 简介

    spring 是面向切面(Aspect Oriented Programming) 和控制反转(Inversion of Control) 的容器框架。

    控制反转是应用本身不负责依赖对象的创建及维护,依赖对象的创建及维护是由外部容器负责的。这样控制权就由应用转移到了外部容器,控制权的转移就是所谓反转

    我们把依赖对象交给外部容器负责创建,那么就需要注入到应用中来,在运行中,将外部对象注入到应用中,我们叫做依赖注入

    那么spring 是轻量级还是重量级呢?

    判断一个应用是轻量级还是重量级,看它使用了多少服务,使用的服务越多,容器要为普通java对象做的工作就越多,那么势必就会影响应用发布的时间或者运行性能

    对于spring容器而言,他提供了很多服务,单这些服务不是默认打开的,如果只使用spring核心服务就是轻量级,如果使用了很多服务,就是重量级

    二、环境

    使用Spring 需要的jar包

    1.单单使用spring

    spring.jar、commons-logging.jar

    2.使用切面还需要引入

    aspectjweaver.jar、aspectjrt.jar、cglib-nodep-2.1_3.jar

    3.使用注解还需要引入

    common-annotations.jar

    三、spring入门

    1.添加java类

    public class PersonDaoBean implements PersonDao {
        /* (non-Javadoc)
         * @see test.spring.dao.Impl.PersonDao#add()
         */
        @Override
        public void add(){
            System.out.println("this is personDaoBean.add()");
        }
    }

    2.添加配置文件 

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
            xmlns:context="http://www.springframework.org/schema/context"
           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
               http://www.springframework.org/schema/context
               http://www.springframework.org/schema/context/spring-context-2.5.xsd "
               >
        <bean id="personDao1" class="test.spring.dao.Impl.PersonDaoBean" ></bean>
    </beans>

    3.在测试中读取配置文件

    AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
            PersonDao personDao= (PersonDaoBean) ctx.getBean("personDao1")

     注:配置文件的取名可以任意,文件可以存放在任何目录下,但考虑到通用性,一般放在类路径下。

    四、配置文件

    1.三种实例化bean的方法

    (1)、使用类构造器

    <bean id="personDao1" class="test.spring.dao.Impl.PersonDaoBean" >

    (2)、使用静态工厂方法

    <bean id="personService" class="cn.itcast.service.OrderFactory" factory-method="createOrder"/>

    java代码

    public class OrderFactory {
        public static OrderServiceBean createOrder(){
            return new OrderServiceBean();
        }
    }

    注,这边写类路径的是class="";

    (3)、使用实例工厂方法

    <bean id="personServiceFactory" class="cn.itcast.service.OrderFactory"/>
    <bean id="personService" factory-bean="personServiceFactory" factory-method="createOrder"/>

    java代码

    public class OrderFactory {
        public OrderServiceBean createOrder(){
            return new OrderServiceBean();
        }
    }

    注,这边写的是factory-bean

    2.作用域

    每次外部容器实例化对象的时候,都是同一个对象。如果想要每次获取都是获取一个新的对象则需要 scope= 'prototype'

    <bean id="personDao1" class="test.spring.dao.Impl.PersonDaoBean"  scope='prototype'></bean>

    3.初始化实例对象

    (1)没有指定范围时,系统默认为一个对象,则加载的时候就初始化了。

            AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");

    即在加载配置文件的时候就初始化话了

    (2)指定作用范围是,系统默认获取对象bean的时候,初始化这个实例

            AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
            PersonServiceBean personService = (PersonServiceBean) ctx.getBean("personServiceBean");//初始化        

    (3)若想共用对象,不适用scope ,但是要获取bean的时候,则需要使用lazy-init

    <bean id="personDao1" class="test.spring.dao.Impl.PersonDaoBean"  lazy-init ="true"></bean>

    (4)若想所有的对象都延迟加载 则在beans 标签里加上 default-lazy-init

    <beans xmlns="http://www.springframework.org/schema/beans"
            xmlns:context="http://www.springframework.org/schema/context" 
           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
               http://www.springframework.org/schema/context 
               http://www.springframework.org/schema/context/spring-context-2.5.xsd "
     default-lazy-init='true'           
    >
    </beans>

     4、初始化需要执行的方法、销毁对象是需要执行功能的方法

    (1)适用所有bean

    <beans xmlns="http://www.springframework.org/schema/beans"
            xmlns:context="http://www.springframework.org/schema/context" 
           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
               http://www.springframework.org/schema/context 
               http://www.springframework.org/schema/context/spring-context-2.5.xsd "
                default-destroy-method="" default-init-method="">
    </beans>

    (2)针对具体的bean

    <bean id="personService" class="test.spring.service.Impl.PersonServiceBean"
            scope="prototype" init-method="init" destroy-method="destroy">

    五、依赖注入

    依赖注入有三种方式:构造器、属性、注解

    1、构造器

    参数使用constructor-arg、index、type 具体指明哪个类型

    java类

        public PersonServiceBean(PersonDao personDao,String name){
            this.personDao = personDao;
            this.name = name;
        }

    beans.xml

        <bean id="personService" class="test.spring.service.Impl.PersonServiceBean"
            scope="prototype">
            <constructor-arg index="0" ref='personDao'></constructor-arg>
            <constructor-arg index="1" value="Sophia"></constructor-arg>
            </bean>

    2.属性

    属性通过property来,属性的类型一般有基本类型、依赖对象、集合(set、List、Map)、properties

        <bean id="personService" class="test.spring.service.Impl.PersonServiceBean"
            scope="prototype">
                   <property name="personDao" ref="PersonDaoBean">        
            <property name="personDao">
                <bean class="test.spring.dao.Impl.PersonDaoBean"/>   
            </property>
            <property name="name" value="Sophia"></property>
            <property name="names">
                <set>
                    <value>Sophia</value>
                    <value>willion</value>
                    <value>colson</value>
                </set>
            </property>
                     <property name="names">
                <list>
                    <value>Sophia</value>
                    <value>willion</value>
                    <value>colson</value>
                </list>
            </property>
            <property name="properties">
                <props>
                    <prop key="name">Sophia</prop>
                    <prop key="pwd">password</prop>
                    <prop key="addr">YanCheng</prop>
                </props>
            </property>
            <property name="infomations">
                <map>
                  <entry key="name" value="XiaoMing"></entry>
                  <entry key="pwd" value="youGuess"></entry>
                </map>
            </property>
        </bean>    

    3.注解

    (1)在xml中配置解析注解的处理器

    <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-2.5.xsd
               http://www.springframework.org/schema/context
               http://www.springframework.org/schema/context/spring-context-2.5.xsd">
              <context:annotation-config/>
    </beans>

    这个配置隐式注册了多个对注释进行解析处理的处理器:AutowiredAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessor,PersistenceAnnotationBeanPostProcessor,RequiredAnnotationBeanPostProcessor
    (2)在java 代码中使用@autowired 和@resource注解方式

    @autowired 是指按照类型类装配

    @resource 是指按照名称来匹配、找不到名称按照类型来匹配

    @autowired(require=true)  要求依赖对象必须存在

    @autowired(require = false ) 先按照类型进行查找如果查找不到,则赋值为null

    @autowired@Qualifier("personDaoBean") 按照名称来装配
    @Resource(name=" ")按照执行的名称来装配 如果没有指定name属性,并且按照默认的名称仍然找不到依赖对象时, @Resource注解会回退到按类型装配。但一旦指定了name属性,就只能按名称装配了。

    六.装配依赖对象方式

    装配依赖对象方式有两种:手工装配、自动装配

    手动装配则是指的上面的配置构造器、属性、注解方式指定
    自动装配则是指的是通过执行的方式系统来自动装配,因为自动装配会产生未知情况,开发人员无法预见最终的装配结果,所以不建议使用。

    1.自动装配

    (1)byName

         把与bean的属性具有相同名字或者(ID)的其他bean 自动进行装配到bean中, 如果没有和属性的名字相匹配的bean,该属性不进行装配   

    <bean id="personService" class="test.spring.service.Impl.PersonServiceBean"
             autowire="byName"/>

     (2) byType

       把与bean的属性具有相同类型的其他bean 自动进行装配到bean中,如果没有不进行装配 

    <bean id="personService" class="test.spring.service.Impl.PersonServiceBean"
             autowire="byType"/>

     (3) constructor

      把与bean的构造器入参具有相同类型的其他bean自动装配到bean构造器的对应入参中

    <bean id="personService" class="test.spring.service.Impl.PersonServiceBean"
             autowire="constructor"/>

     (4) autodetect

      首先尝试使用construcor进行自动装配。如果失败,在尝试使用bytype进行自动装配

    2.手工装配

    手工装配依赖对象,有两种编程方式
    (1)、在xml配置文件中,通过在bean节点下配置 构造器、属性

    (2)、在java代码中使用@Autowired或@Resource注解方式进行装配。同时需要在xml中引入注解进行解析处理的处理器

    七、组件自动扫描

    自动扫描机制,他可以在类路径底下寻找标注了@Component、@Service、@Controller、@Repository注解的类,并把这些类纳入进spring容器中管理。它的作用和在xml文件中使用bean节点配置组件是一样的。

    @Service用于标注业务层组件

    @Controller用于标注控制层组件(如struts中的action)

    @Repository用于标注数据访问组件,即DAO组件。

    @Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。
    1.配置xml文件

    <beans xmlns="http://www.springframework.org/schema/beans"
            xmlns:context="http://www.springframework.org/schema/context" 
           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
               http://www.springframework.org/schema/context 
               http://www.springframework.org/schema/context/spring-context-2.5.xsd "
                default-destroy-method="" default-init-method="">
        <context:annotation-config/>
        <context:component-scan base-package="test.spring"></context:component-scan>
    </beans>

    2.在java类加上注解

    import test.spring.dao.PersonDao;
    @Repository("PersonDao") 
    public class PersonDaoBean implements PersonDao {
        /* (non-Javadoc)
         * @see test.spring.dao.Impl.PersonDao#add()
         */
        @Override
        public void add(){
            System.out.println("this is personDaoBean.add()");
        }
    }

    3.测试类加载

            AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
            PersonServiceBean personService = (PersonServiceBean) ctx.getBean("personServiceBean");
            

     没有指定名称则默认类的简单名称 即类名首字母小写

    也可以名称@Repository("PersonDao")

    使用注解的方式默认也是共用一个实例对象 ,如果要每次加载都获取到实例对象则@Repository("PersonDao") @Scope("prototype")

    指定初始化方法 @postConstruct

    指定销毁对象 @predestroy

        
        public PersonServiceBean(){
            
        }
        @PostConstruct
        public void init(){
            System.out.println("hello Person");
        }
        @PreDestroy
        public void destroy(){
            System.out.println("destroy Person");
        }
        
  • 相关阅读:
    Lua调用C++时打印堆栈信息
    Node.js批量去除BOM文件
    cocos2d-x中CCLabelAtlas的小图片拼接
    node.js使用mysql模块的坑
    关于chrome插件编写的小结
    【吐槽】如风达快递
    bat调用TexturePacker更新SpriteSheet
    使用node-webkit实现打包工具的小结
    使用devenv.exe自动编译项目
    svn导出文件进行比较
  • 原文地址:https://www.cnblogs.com/Keep-Going-Space/p/5069796.html
Copyright © 2011-2022 走看看