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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章