spring笔记整理0928(一)

来源:互联网 发布:大数据 论文 编辑:程序博客网 时间:2024/05/22 00:23

bean配置项

id:bean的id,唯一标识,可以在getbean的时候指定注入对象,一个对象的引用

class:注入的类,具体实现哪个类

scope:scope的作用域。默认是单例模式,即scope="singleton"。另外scope还有prototype、request、session、global session作用域。

   

Constructorarguments:构造器参数

Properties:属性,构造器注入用到constructor arguments和properties

Autowiring mode:自动装配模式

Lazy-initializationmode:懒加载模式

Initialization/destructionmethod:自动初始化和摧毁方式


scope使用

默认是单例模式:

Xml中配置

<beanid="testDao"class="com.hh.dao.TestDaoImpl"/>

   <beanid="testService"class="com.hh.service.TestServiceImpl"scope="singleton">

      <propertyname="testDao"ref="testDao"/>

   </bean>

测试类:

@Test publicvoid test0925(){

       ApplicationContext context =newClassPathXmlApplicationContext("spring-core.xml");

       TestService testService1=(TestService)context.getBean("testService");

       System.out.println("testService1:"+testService1.hashCode());

       TestService testService2=(TestService)context.getBean("testService");

       System.out.println("testService2:"+testService2.hashCode());

    }

 

运行结果:哈希码是一致的,表示同一个对象



使用prototype

 

Xml中配置

<beanid="testDao"class="com.hh.dao.TestDaoImpl"/>

   <beanid="testService"class="com.hh.service.TestServiceImpl"scope="prototype">

      <propertyname="testDao"ref="testDao"/>

   </bean>

 

测试类:

@Test publicvoid test0925(){

       ApplicationContext context =newClassPathXmlApplicationContext("spring-core.xml");

       TestService testService1=(TestService)context.getBean("testService");

       System.out.println("testService1:"+testService1.hashCode());

       TestService testService2=(TestService)context.getBean("testService");

       System.out.println("testService2:"+testService2.hashCode());

    }

 

测试结果:(不同的对象,哈希值也不同)



Bean的生命周期





使用默认的构造器注入自动装配:

default-autowire="constructor"

 

Resources:所有的applicaionContext都实现了resourcesLoader接口中的getResources方法,通过该方法可以获得resources.

1.在spring规定中,resources文件夹是访问资源的入口。

2.classPath:xxx/src/main

3.getResources()方法的参数:classPath方式: classPath:xxx.txt

4.file方式: file:D:\\...\\xxx.txt

5.url方式: url:http://.../.../xxx

6.没有前缀时依赖applicationContext的配置文件路径:即使用配置文件的路径