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制定具体的对象
  • 相关阅读:
    从员工到总监,我的7个经验心得(转)
    对上司不满,说还是不说
    老子智慧-大道甚夷
    实际操作中命令 su 与 sudo 的区别(转)
    杨氏矩阵查找元素位置Java实现
    Java实现 蓝桥杯 算法提高 周期字串
    Java实现 蓝桥杯 算法提高 周期字串
    Java实现 蓝桥杯 算法提高 学霸的迷宫
    Java实现 蓝桥杯 算法训练 最大最小公倍数
    Java实现 蓝桥杯 算法训练 最大最小公倍数
  • 原文地址:https://www.cnblogs.com/roxy/p/7576553.html
Copyright © 2011-2022 走看看