IOC与DI总结

193 阅读2分钟
  1. 编写流程(基于XML)

    1. 导入jar包: 4+1 -> beans / core / context / expression | commons-logging
    2. 编写目标类:dao和service
    3. spring配置文件
      1. IoC:<bean id="" class="">
      2. DI:<bean><property name="" value="" ref=""></bean>
      3. 实例化方式:
        1. 默认构造
        2. 静态工厂:<bean id="" class="工厂类" factory-method="静态方法"/>
        3. 实例工厂:<bean id="" factory-bean="工厂id" factory-method="方法">
      4. 作用域:<bean id="" scope="singleton|porotype">
      5. 生命周期:<bean id="" class="" init-method="" destory-method="">
        1. 后处理bean BeanPostProssor接口,<bean class="注册">对容器中所有的bean都生效
      6. 属性注入
        1. 构造方法注入:<bean><constructor-arg index="" type="">
        2. setter方法注入:<bean><property>
        3. p 命名空间:简化<property> <bean p:属性名="普通值" p:属性名-ref="引用值"> 注意生明命名空间
        4. SpEL:<property name="" value="#{表达式}">
          1. #{123} #{‘abc’}
          2. #{beanId.propName?methodName()}
          3. #{T(类).静态方法|字段}
        5. 集合
          1. 数组<array>
          2. List<list>
          3. Set<set>
          4. Map<map><entry key="" value="">
          5. Propertes<props><prop key="">....
    4. 核心api
      1. BeanFactory:延迟实例化bean,第一次调用getBean
      2. ApplicationContext 一般常用,功能更强
        1. ClassPathXmlApplicationContext 加载 classpath xml文件
        2. FileSystemXmlApplicationContext 加载 指定盘符文件,ServletContext.getRealPath();
  2. 注解

    1. 扫描含有注解的类 1.<context:component-scan base-package="">
    2. 常见的注解
      1. Component 组件,任意bean
      2. WEB
        1. @Controller web层
        2. @Service service层
        3. @Repository dao层
      3. 注入 --》 字段或者setter方法
        1. 普通值:@Value
        2. 引用值:
          1. 类型:@Autowired
          2. 名称1:@Autowired @Qualifier("名称")
          3. 名称2:@Resource(“名称”)
      4. 作用域:@Scope("prototype")
      5. 生命周期:
        1. 初始化:@PostConstruct
        2. 销毁方法:@PreDestroy
  3. 注解和xml混合使用

    1. 将所有的bean都配到xml中

      1. <bean id="" class="">
    2. 将所有的依赖都使用注解

      1. @Autowired

        默认不生效。为了生效,需要在xml配置<context:annotation-config >

         <context:component-scan base-package="com.adolph.web"></context:component-scan>
         
         <context:annotation-config></context:annotation-config>
     1. 一般情况两个注解不一起使用
     2. 注解一,扫描含有注解(@Component等)类,注入注解自动生效
     3. 注解为,只在xml和注解(注入)混合使用时,使注入注解生效。