Spring

1 Autowire自动装配
1.1 使用:只需在<bean>中使用autowire元素
<bean id="student" class="com.kejian.spring.bean.autowire.Student"
p:name="Tony" autowire="byName"></bean>

1.2 类型 
byName 目标bean的id与属性名一置,若不匹配置为null
byType 根据引用类型,若有多个bean无法装配,会抛异常
constructor(不推荐)

1.3 自动装配的缺点
若使用autowire装配bean ,则会装配全部属性;
autoName和autoType不能混合使用;
实际项目一般少用到

2 bean之间的关系
2.1 继承关系
2.1.1 可使用<bean>的parent属性配置继承父类(模板)
2.1.2 子bean可以继承父bean的属性,也可以覆盖部分属性
2.1.3 父bean可以作为实例,也可以作为模板,可以设置<bean>的abstract=true,则该bean为抽象bean,
不能被实例化,
2.1.4 父bean若没有设置任何属性,则默认为abstract

<bean id="subject" class="com.kejian.spring.bean.autowire.Subject" 
p:id="1" p:name="Chinese" abstract="true"></bean>

<bean id="subject2" class="com.kejian.spring.bean.autowire.Subject" 
parent="subject" p:id="2" p:name="History"></bean>


2.2 依赖关系
2.2.1 Spring允许通过使用depends-on属性设定bean的前置bean,依赖的bean必须在本bean实例化前创建好
2.2.2 如果依赖多个bean,可以使用逗号或空格的方式隔开
<!-- bean的依赖关系 -->
<bean id="student" class="com.kejian.spring.bean.autowire.Student"
p:name="Tim" p:subject-ref="subject3"></bean>

3 bean的作用域
3.1 默认为singleton,创建容器时就实例化好,每次获取时返回同一个实例
<bean id="car" class="com.kejian.spring.Car"
p:brand="ToYoTa" p:corp="GuangZhou" p:price="15" scope="prototype"></bean>

3.2 可以使用scope进行配置

4 使用外部属性文件
4.1 bean配置有时需要系统部署信息,如文件路径、数据源配置信息等,需要将其与bean配置文件分离
4.2 Spring 提供了一个 PropertyPlaceholderConfigurer 的 BeanFactory 后置处理器,可以使用外部属性文件,使用${var}
4.3 spring2.5后,可通过<context:property-placeholder> 直接使用PropertyPlaceholderConfigurer ,使用locaiton属性指明配置文件路径,需要引入context schema
<!-- 引入外部属性文件 -->
<context:property-placeholder location="db.properties"/>

db.properties与properties.xml必须同级目录,否则会报错,

class path resource [db.properties] cannot be opened because it does not exist

<!-- 使用外部属性配置文件-->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="datasource2" class="com.spring.bean.properties.DbProperties">
<!-- 为属性赋值 赋值位置必须使用jdbc.userName这种形式,否则输出用户名为administrator,同时db.properties也必须为jdbc.userName这种形式-->
<property name="userName" value="${jdbc.userName}"></property>
<property name="passWord" value="${jdbc.passWord}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
</bean>

原文地址:https://www.cnblogs.com/longronglang/p/6179194.html