1. 認識Spring註解
Spring目前是目前最最最火的Java框架,而且在這基礎上發展的SpringBoot,SpringCloud也都有很多人用,我們已經習慣了使用註解的方式開發,所以也可以瞭解Spring註解驅動發展的過程。
2. Spring註解發展歷程
2.1 Spring1.x註解驅動啓蒙階段
此時Java5剛剛發佈,正在流行Annotation風格,Spring1.2提供了@Transactional和@ManagedResource,但是此時裝載Bean還是通過XML配置的方式
<bean name="DemoSerivce"
class="com.tiger.example.spring.v1.DemoService01"/>
2.2 Spring2.x註解驅動發展重要階段
- Spring2.0發展了@Required,@Repository,@Aspect等
- Spring2.5提供了非常重要的註解@Autowired@Qualifier以及@Component@Service@Controller等註解,這些都是我們現在開發中還在使用的註解
此時Spring並沒有完全去XML化,還需要通過在XML中配置
<context:component-scan
base-package="com.tiger.example.spring.v2"></context:component-scan>
2.3 Spring3.x註解驅動的里程碑
- Spring3.0中提供了@Configuration註解,此時可以完完全全的去XML化配置
@Configuration
public class SpringConfiguration {
@Bean
public DemoService03 getDeDemoService03(){
return new DemoService03();
}
}
- @ComponentScan(basePackages="")配置掃描的路徑
- @Import導入其他配置類進行裝載
@Configuration
@Import(ImportConfiguration.class) //掃描ImportConfiguration配置類並且加載
public class SpringConfiguration {
@Bean
public DemoService03 getDeDemoService03(){
return new DemoService03();
}
}
@Configuration
public class ImportConfiguration {
@Bean
public ImportService getImportService(){
return new ImportService();
}
}
- @EnableXXX可以模塊化的裝載 eg:快速開啓定時任務
@Configuration
@EnableScheduling
public class ScheduleConfiguration {
@Bean
public ScheduleService getScheduleService(){
return new ScheduleService();
}
}
2.4 Spring4.x註解完善階段
Spring4.x提供了@Conditional註解,用來可以自定義條件完成Bean的初始化
@Configuration
public class SpringConfiguration {
//條件註解 如果TigerCondition返回true初始化,否則不初始化
@Conditional(TigerCondition.class)
@Bean
public DemoService getDemoService(){
return new DemoService();
}
}
public class TigerCondition implements Condition {
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
// TODO 這裏可以實現很多業務邏輯處理
//返回false時 bean不實例化
//return false;
//返回true時 bean實例化
return true;
}
}
2.5 Spring5.x註解優化階段
@Indexed是爲了提升在ComponentScan掃描的性能 細節可以參考這裏
Spring5–@Indexed註解
3. 小知識
3.1 Spring如何解決循環依賴
如果Class A和ClassB爲循環依賴
- 原則 Spring初始化Bean的順序是 首先初始化當前Bean,在初始化依賴Bean
- A中依賴B 首先初始化A 發現A中有B 此時A是半成品狀態
- 初始化B B中有A 將半成品的A對象設置到B中 B完成初始化
- 然後A完成初始化
4. 總結
Spring2.x註解驅動的發展重要時期,提供了很多實用的註解,再到後面完全去XML配置以及提升性能,使Spring更受歡迎!
代碼位置: tiger-spring-demo