Spring--官方文檔部分翻譯(第一章)

1.6.1 Bean生命週期

控制生命週期的按照方式

  • InitializingBean 和 DisposableBean回調接口
  • 自定義init() and destroy() 方法
  • @PostConstruct and @PreDestroy 註解
    初始化執行次序:
    @PostConstruct—InitializingBean接口的afterPropertiesSet()方法–(BeanPostProcessor的回調方法)–自定義init方法(…)@PreDestroy—DisposableBean接口的destroy方法—自定義destroy方法
  • 不建議使用InitializingBean接口,建議使用@Bean中的“initMethod”屬性
  • 不建議使用DisposableBean接口,建議使用@Bean中的“destroyMethod”屬性

1.8.1 通過BeanPostProcessor自定義Bean

  • 如果想在Spring容器完成實例化和bean初始化後實現自定義邏輯,可以實現BeanPostProcessor的回調方法
  • Spring容器實例化bean,BeanPostProcessor使bean開始工作

1.8.2 通過BeanFactoryPostProcessor自定義配置元數據

1.8.3 通過FactoryBean自定義實例化邏輯

1.9 基於註解的容器配置

註解是否優於xml配置?

  • 各有優劣,取決於具體情況
  • 註解實現更爲簡潔和精準
  • xml可以免編譯執行,在一些場合更適合
  • 兩者同時出現時,xml會覆蓋註解

1.9.1 @Required

1.9.2 @Autowired

1.9.3 @Primary

1.9.4 @Qualifier

1.9.6 CustomAutowireConfigurer

  • 是一種BeanFactoryPostProcessor,可以註冊自定義的qualifier註解類型

1.9.7 @Resource(JDK5、6中使用較多)

1.9.8 @PostConstruct and @PreDestroy

1.10 Classpath掃描和組件管理

1.10.1 @Component等

  • @Component是普通的spring組織的註解,@Repository, @Service, and @Controller是特定應用場景下對@Component的專業化實現。

1.10.2 組合註解

  • @RestController相當於@Controller and @ResponseBody的組合

1.10.3 自動類探測,註冊bean

  • 使用@ComponentScan 修飾@Configuration類,其中的basePackages屬性爲類所在的父package
  • 使用@ComponentScan時,AutowiredAnnotationBeanPostProcessor會被默認調用(???)。
@ComponentScan(basePackages = "org.example")
@ComponentScan("org.example")

1.10.4 使用Filters來自定義掃描

  • 設置:useDefaultFilters選項
@Configuration
@ComponentScan(basePackages = "org.example",
        includeFilters = @Filter(type = FilterType.REGEX, pattern = ".*Stub.*Repository"),
        excludeFilters = @Filter(Repository.class))
public class AppConfig {
    ...
}

1.10.5 在Component中定義Bean元數據(待深化)

  • 使用@Bean註解修飾方法
  • @Bean可修飾靜態方法,使得他們被調用時不會再生成所包含的配置(爲了安全起見)
  • 靜態@Bean方法的調用不會被Spring容器所攔截,這是由於CGLIB中子類只能覆蓋非static類
  • As a consequence, a direct call to another @Bean method has standard Java semantics, resulting in an independent instance being returned straight from the factory method itself.
  • 通常情況下,@Bean修飾的方法不能聲明爲private以及final,因爲他們需要是可覆蓋的。

1.10.6 命名可自探測的Component

  • 這類Component通過BeanNameGenerator生成,可以自定義該接口的實現

1.11 使用JSR 330註解

1.11.1 @Inject and @Named

  • 可以實現@Autowired功能,默認byType注入
  • 如果需要nyName注入,則使用@Name
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章