zoukankan      html  css  js  c++  java
  • Spring 基础使用

    1 id 和 name 的区别

       id:不可重复,不可包含特殊字符

      name:可以重复,可以包含特殊字符

    2 scope

      singleton:配置单例模式(默认),在容器启动时创建对象,而且只创建一个

      prototype:配置多例模式,在容器启动时不创建对象,当获取对象时才创建

    3 lazy-init

      true:延迟创建对象,容器启动时不创建,获取时再创建,只适用于单例模式

      false:(默认)

     4 init-method 和 destroy-mothod

      init-method:初始化调用方法

      destroy-mothod:销毁时调用方法

    config:

    <bean name="p1" id="p2" scope="singleton" lazy-init="true" init-method="init" destroy-method="destroy" class="com.roxy.spring.pojo.Person"></bean>

    test:
       
       @Test
        public void testIdAndName() {
            
            //创建容器
            AbstractApplicationContext  context = new ClassPathXmlApplicationContext("applicationContext.xml");
            
            //查找对象
            Person p1 = (Person)context.getBean("p1");
            Person p2 = (Person)context.getBean("p1");
            
            context.destroy();//执行销毁
    //        context.close();//触发销毁
            
        }
       
    console:
      
        Creating shared instance of singleton bean 'p2'
        Creating instance of bean 'p2'
        构造方法被调用
        Eagerly caching bean 'p2' to allow for resolving potential circular references
        Invoking init method  'init' on bean with name 'p2'
        Person被初始化!
        Invoking destroy method 'destroy' on bean with name 'p2'
        Person被销毁!
       

    5 注解式开发:

    注意导入包以及添加命名空间

    <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"
        xmlns:p="http://www.springframework.org/schema/p"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">
       
       <context:component-scan base-package="com.roxy.spring.pojo"></context:component-scan>
     
    </beans>


    在使用注解式开发,@Autowired自动装配引入对象类型的时候,会出现一个类型对应多个对象的问题

    eg:
      
      car1{
        name : 小黄车
        color : yellow
      }
      car2{
        name : 小蓝车
        color:blue
      }
      person{
        name : draco
        age : 17
        car : ?
      }
        
      使用@Qualifiter指定具体的对象
      使用@Resource制定具体的对象
  • 相关阅读:
    Django动态下载文件
    单反学习
    网页开发
    从一堆数中随机取出一些值的方法
    C/C++使用HTTP协议上传
    django 初级(一) 配置与周边
    c++11
    外观模式
    sqlite
    linux程序设计1
  • 原文地址:https://www.cnblogs.com/roxy/p/7576553.html
Copyright © 2011-2022 走看看