ClassPathXmlApplicationContext與FileSystemXmlApplicationContext的區(qū)別:
ClassPathXmlApplicationContext使用方法:(classpath路勁查找)
ClassPathXmlApplicationContext 默認會去 classPath 路徑下找。classPath 路徑指的就是編譯后的 classes 目錄。
FileSystemXmlApplicationContext使用方法(項目路徑或者相對路徑)
FileSystemXmlApplicationContext 默認是去項目的路徑下加載,可以是相對路徑,也可以是絕對路徑,若是絕對路徑,“file:” 前綴可以缺省。
配置Spring bean元數(shù)據(jù)的方式
- 基于 XML 配置
- 基于 注解 配置:Spring2.5以上版本支持
- 基于Java 配置:Spring3.0以上版本支持
注入的方式:
- Constructor構造器注入: Setter屬性方法注入 使用構造方法的參數(shù),做為注入的通道。
- Setter屬性方法注入: 使用屬性對應的Setter方法參數(shù),做為注入的通道。
使用Setter注入,請確保當前類擁有無參構造方法.
構造注入三種方式標明方法中的參數(shù):
1.type 根據(jù)數(shù)據(jù)類型
2.index 根據(jù)順序
3.name 根據(jù)參數(shù)名
ref與value的區(qū)別
- ref傳入引用
- value傳入值
<bean id="repostitoryBean1" class="com.apesource.repostitory.Repostitory1">
</bean>
<bean id="repostitoryBean2" class="com.apesource.repostitory.Repostitory2">
</bean>
<bean id="serviceBean1" class="com.apesource.service.Service1">
<!--構造方法注入-->
<constructor-arg name="irepostitory" ref="repostitoryBean1"></constructor-arg>
<!--setter注入-->
<property name="irepostitory" ref="repostitoryBean1"></property>
</bean>
注入list 、set、map、props類型的集合數(shù)據(jù)。
仍保留集合了特性。




Spring中的自動組裝
autowire屬性設置自動組裝參數(shù)
- no默認,關閉自動組裝。
- byName,按名稱自動組裝,Spring會查找 相同名稱的屬性Setter進行注入。
- constructor,類似于按類型自動組裝,Spring會 查找相同類型的構造器進行注入。
- byType,按類型自動組裝,Spring會查找 相同類型的屬性Setter進行注入。
使用注解完成自動化裝配bean
類級別注解:
@Component:表明該類會作為組件 類,并告知Spring要 為這個類創(chuàng)建bean。
@ComponentScan:啟用組件掃描, 默認當前配置類 所在包為基礎包。
basePackages : 基礎包 basePackageClasses: 指定類所在包為基礎包
@Primary:(一 般與@Component 配合使用)在自動裝配時,設置 某個bean為首選。
方法級別注解:
@Autowired:自動注入一個符 合類型要求的 bean
required: 是否為必須注入項。
@Qualifier:指定所注入的 bean的ID
value: 所注入的bean的ID
@Scope:定義bean的作用域。
Java Config
@Configuration:定義Spring配置類
@Bean:聲明配置該方法所 產(chǎn)生的對象為 Spring中的bean
導入和混合配置
@Import:導入其他配置類
@ImportResouce:導入其他XML配置文件