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制定具体的对象
  • 相关阅读:
    Intellij使用心得(四) -- 导入Eclipse的代码格式化文件
    idea安装插件plugin(主要针对网络连接不上的情况)
    IDEA破解方法以及快捷键大全
    eclipse+maven搭建自己web系统的骨架,解决自带骨架加载无限慢的问题
    用Eclipse创建Maven多模块项目
    Maven实战--- dependencies与dependencyManagement的区别
    redis之有序集合类型(Zset)——排行榜的实现
    做一个完整的Java Web项目需要掌握的技能
    经典面试题:用户反映你开发的网站访问很慢可能会是什么原因
    linux 免密码 使用sudo 直接使用root权限执行命令
  • 原文地址:https://www.cnblogs.com/roxy/p/7576553.html
Copyright © 2011-2022 走看看