Spring实战读书笔记 第三章 最小化 Spring XML配置

1,自动装配(autowiring)有助于减少甚至消除配置<property>元素,让Spring自动识别如何装配Bean的依赖关系。
2,自动检测(autodiscovery)让Spring自动识别那些类需要配置为Spring Bean,减少<bean>元素使用。
3,四种自动装配:
    -1,byName:把与Bean的属性具有相同名字(或者ID)的其他Bean自动装配到Bean的对应属性中,如果没有跟属性名字相匹配的Bean,则该属性不进行装配。
    -2,byType:把与Bean的属性具有相同类的其他Bean自动装配到Bean对应的属性中去。如果不存在,则不进行装配。
    -3,constructor:把与Bean的构造入参具有相同类型的其他Bean自动装配到Bean的构造参数中。
    -4,autodetect:首先尝试constructor进行自动装配,如果失败则尝试byType。
byName自动装配:
如下代码为普通的装配
   
   
<bean id="kenny2" class="chp02.springdol.Instrumentalist">
<property name="song" value="122132"></property>
<property name="inst" ref="sandbox"></property>
</bean>
<bean id="sandbox" class="chp02.springdol.Saxophone"></bean>

使用byName自动装配:
   
   
<bean id="kenny2" class="chp02.springdol.Instrumentalist" autowire="byName">
<property name="song" value="122132"></property>
</bean>
<bean id="inst" class="chp02.springdol.Saxophone"></bean>
byName自动装配遵循:为属性自动装配ID与该属性的名字相同的Bean。
byType自动装配:
byType自动寻找类型相同的Bean注入,如果Spring找到多个类型匹配的类,那么会抛出异常。为了避免这点,可以设置首选bean。
constructor自动装配,与其他类似。
4,设置默认制动装配, default-autowire
   
   
<?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:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd" default-autowire="byType">
5,使用注解装配。
   
   
<?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:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd" default-autowire="byType">
 
<context:annotation-config/>
</beans>
使用 < context : annotation - config />启用注解:
-1,使用@Autowired
   
   
@Autowired
public void setInstrument(Instrument instrument) {
this.instrument = instrument;
}
使用注解标识当前成员变量或者bean使用自动注入。
6,自动检测标注Bean:
         -1,@Component:通用的构造型注解,标识该类为Spring组件。
        -2,@Controller:标识该类为Spring MVC Controller。
        -3,@Repository:标识该类为数据仓库。
        -4,使用@Component标注任意自动一注解。

























    



















































评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值