spring官网学习记录

  • ApplicationContext实现还允许注册在容器外部(由用户)创建的现有对象。这是通过通过方法访问ApplicationContext的BeanFactory来完成的getBeanFactory(),该方法返回BeanFactory DefaultListableBeanFactory实现。DefaultListableBeanFactory 通过registerSingleton(..)和 registerBeanDefinition(..)方法支持此注册。但是,典型的应用程序只能与通过常规bean定义元数据定义的bean一起使用。Bean元数据和手动提供的单例实例需要尽早注册,以便容器在自动装配和其他自省步骤中正确地推理它们。虽然在某种程度上支持覆盖现有元数据和现有单例实例,但官方不支持在运行时(与对工厂的实时访问同时)对新bean的注册,并且可能导致并发访问异常,bean容器中的状态不一致或都。
  • bean实例化

用构造函数实例化 


 用静态工厂方法实例化



public class ClientService {
    private static ClientService clientService = new ClientService();
    private ClientService() {}

    public static ClientService createInstance() {
        return clientService;
    }
}

使用实例工厂方法实例化



    





public class DefaultServiceLocator {

    private static ClientService clientService = new ClientServiceImpl();

    public ClientService createClientServiceInstance() {
        return clientService;
    }
}
  • 自定义bean的性质

从Spring 2.5开始,您可以使用三个选项来控制Bean生命周期行为:

  • InitializingBean和 DisposableBean回调接口

  • 习惯init()destroy()方法

  • @PostConstruct@PreDestroy 注释。您可以结合使用这些机制来控制给定的bean。

为同一个bean配置的具有不同初始化方法的多种生命周期机制如下:

  1. 用注释的方法 @PostConstruct

  2. afterPropertiesSet()InitializingBean回调接口定义

  3. 定制配置的init()方法

销毁方法的调用顺序相同:

  1. 用注释的方法 @PreDestroy

  2. destroy()DisposableBean回调接口定义

  3. 定制配置的destroy()方法

Aware 接口

名称 注入依赖

ApplicationContextAware

宣告ApplicationContext

ApplicationEventPublisherAware

附件的事件发布者ApplicationContext

BeanClassLoaderAware

Class loader used to load the bean classes.

BeanFactoryAware

宣告BeanFactory

BeanNameAware

声明bean的名称。

BootstrapContextAware

BootstrapContext容器在其中运行的资源适配器。通常仅在支持JCA的ApplicationContext实例中可用。

LoadTimeWeaverAware

Defined weaver for processing class definition at load time.

MessageSourceAware

解决消息的已配置策略(支持参数化和国际化)。

NotificationPublisherAware

Spring JMX通知发布者。

ResourceLoaderAware

配置的加载程序,用于对资源的低级别访问。

ServletConfigAware

当前ServletConfig容器在其中运行。仅在可感知网络的Spring中有效 ApplicationContext

ServletContextAware

当前ServletContext容器在其中运行。仅在可感知网络的Spring中有效ApplicationContext

 

你可能感兴趣的:(spring)