spring笔记整理0928(一)
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中配置
<bean id="testDao"class="com.hh.dao.TestDaoImpl"/>
<bean id="testService" class="com.hh.service.TestServiceImpl" scope="singleton">
<property name="testDao" ref="testDao"/>
</bean>
测试类:
@Test public void 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中配置
<bean id="testDao"class="com.hh.dao.TestDaoImpl"/>
<bean id="testService" class="com.hh.service.TestServiceImpl" scope="prototype">
<property name="testDao" ref="testDao"/>
</bean>
测试类:
@Test public void 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的配置文件路径:即使用配置文件的路径