Spring学习03--其他特性(减少配置、自动装配、scope作用域,延迟初始化)

一、如何减少配置
1、将共同特性抽象出来
假设有两个类,Beal1和Bean2,两个类的成员变量都是如下:

private String name;
private int age;
private String sex;

写好get/set方法,那么在配置文件,这三个属性,两个bean标签都需要配置一遍,很麻烦,那么应该如何配置,能够减少配置量呢?

<!-- 公共配置 -->
<bean id="AbstractBean" abstract="true">
  <property name="age" value="100" /> 
  <property name="name" value="zhangsan" /> 
  <property name="sex" value="nan" />   
</bean>

<!-- 配置parent属性为公共配置 -->
<bean id="bean1" class="com.errol.Bean1" parent="AbstractBean">
</bean>
<bean id="bean2" class="com.errol.Bean2" parent="AbstractBean">
</bean>

通过标签将公共的配置提取出来,然后指定标签中的abstract属性为true , 在其他标签中指定其parent即可

2、自动装配
配置Spring为自动装配,属性为default-autowire,类Bean1中有个成员变量:
private Bean2 bean2;
下面的配置为按名称自动装配

  <?xml version="1.0" encoding="UTF-8" ?> 
- <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd" default-autowire="byName">

    <bean id="bean1" class="com.errol.Bean1/>
    <bean id="bean2" class="com.errol.Bean2"/>

<beans>

就按照改配置方法,发现程序也能正常运行,所以自动装配生效了,如何按名称呢,也就是类中的成员变量bean2=bean变量中的id,Spring就能够按照名称自动将属性注入。
还有一种装配方式,就是按照类型,default-autowire=”byType”,顾名思义,就是根据成员变量的属性进行自动装配,这种方法的局限性比上面的要好,按名称自动装配要求名称要有规则。

3、其他属性
1)scope作用域
bean标签中有一个属性scope,这个属性默认为singleton,也就是Spring重复取该对象是同一个

<bean id="bean1" class="com.errol.Bean1" scope="singleton">

该属性还有一个值,表示多次取出为不同scope=”prototype”
验证这种配置可以写一个小程序将Bean1取多次,如果多次取出都为同一个。则scope为singleton配置。

2)延迟初始化
Spring模式在创建BeanFactory对象时,就将配置文件中配置的对象全部初始化出来,当然,我们可以修改
使用属性default-lazy-init=”true” 配置如下:

  <?xml version="1.0" encoding="UTF-8" ?> 
- <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd" default-lazy-init="true">

</beans>

这样配置就是告诉Spring配置文件中的对象,只有在使用时才会被初始化,而不是在BeanFactory创建时初始化。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值