Spring初探

Bean容器初始化

  • 基础:两个包
    1. org.springframework.beans
    2. org.springframework.context
    3. BeanFactory提供配置结构和基本功能,加载并初始化Bean
    4. ApplicationContext保存了Bean对象所在Spring中被广泛使用
  • 方式,ApplicationContext
    1. 本地文件
    2. classpath
    3. Web应用中依赖Servlet或Listener

Spring的常用注入方式

  • 设值注入(必须有set方法)

    <beans>
      <bean id="" class="">
        <property name="" ref=""></property>
      </bean>
      <bean id="" class=""></bean>
    </beans>
    
  • 构造注入

    <beans>
      <bean id="" class="">
        <constructor-arg name="" ref=""></property>
      </bean>
      <bean id="" class=""></bean>
    </beans>
    

专题二

Bean配置项

  • Id
  • Class
  • Scope
  • Construtor arguments
  • Properties
  • Autowiring mode
  • lazy-initialization mode
  • Initialization/destruction method

Bean的作用域

  • singleton:单例,指一个Bean容器中只存在一份
  • prototype:每次请求(每次使用)创建新的实例,destory方式不生效
  • request:每次http请求创建一个实例且仅在当前request内有效
  • session:同上,每次http请求创建,当前session内有效
  • global session:基于portlet的web中有效(portlet定义了global session),如果是在web中,同session

Bean的生命周期

  • 定义

  • 初始化

    1. 实现org.springfrmaework.beans.factory.InitializingBean接口,覆盖afterPropertiesSet方法
    public class ExampleBean implements InitializingBean {
      public void afterPropertiesSet() throws Exception {
        //do something
      }
    }
    
    1. 配置init-method。
    <bean id="" class="" init-method=""></bean>
    
    public class ExampleBean {
      public void init() {
        //do some initialization work
      }
    }
    
  • 使用

  • 销毁

  1. 实现org.springframework.beans.factory.DisposableBean接口,覆盖destroy方法
public class ExampleDisposalBean implements DisposableBean {
  public void destroy() throws Exception {
    //do something
  }
}
  1. 配置destory-method
<bean id="" class="" init-method=""></bean>
public class ExampleBean {
  public void cleanup() {
    //do some destruction work (like releasing pooled connections)
  }
}
  • 配置全局初始化,销毁方法
<beans default-init-method="" default-destroy-method=""></beans>

Aware接口

Bean的自动装配

Resource&ResourceLoader

posted @ 2020-06-03 21:01  iDestro  阅读(71)  评论(1)    收藏  举报