xzc520

 

Spring概念理解

Inversion
of Control Containers(IOC)由容器来控制程序间的关系,而非程序来控制,就是所谓的容器控制反转。
Dependency Injection 容器动态的将某种动态关系注入到主键当中。

依赖注入的几种实现
   type1 接口注入
            public class ClassA {
                  private InterfaceB clzB;
                  public doSomething() {
                        Ojbect obj =
                              Class.forName(Config.BImplementation).newInstance();
                         clzB = (InterfaceB)obj;
                         clzB.doIt()
                  }
            ……
            }
   我们通过配置文件动态的加载类,然后强制转换成相应的类来实现动态注入,对于IOC容器来说加载类的过程由容器来完成。
web容器采用type1 接口注入的具体应用
public class MyServlet extends HttpServlet {
public void doGet(
         HttpServletRequest request,
         HttpServletResponse response)
            throws ServletException, IOException {
      ……
   }
}

Type2 设值注入  它由容器通过Setter方法完成依赖关系的设置
Type3构造了注入 
public class DIByConstructor {
   private final DataSource dataSource;
   private final String message;
   public DIByConstructor(DataSource ds, String msg) {
      this.dataSource = ds;
      this.message = msg;
   }
   ……
}

Bean Wrapper
     由容器将依赖关系注入到组件当中,在运行期间由spring根据配置文件,将其它对象的引用通过组件提供的setter方法进行设定。运行期间动态生成对象并设定它对依赖关系.
Object obj = Class.forName("net.xiaxin.beans.User").newInstance();
BeanWrapper bw = new BeanWrapperImpl(obj);
bw.setPropertyValue("name", "Erica");
System.out.println("User name=>"+bw.getPropertyValue("name"));

Bean Factory
  创建并且维护Bean实例它可以配置
      1.  Bean的属性值及其依赖关系(即对其它Bean的引用)
      2.  Bean的创建模式(是否单例模式)
      3.  Bean的初始化和销毁方法
      4.  Bean的依赖关系

ApplicationContext
      覆盖了BeanFactory所有的方法,而且提供了新的功能。它有以下扩展功能
   1.国际化的支持
   2.资源访问
   3.事件传播
   4.多实例加载
    spring提供了可配置的ApplicationContext加载机制。加载器有两种选择:ContextLoaderListener或ContextLoaderServlet一个利用servlet2.3的Listener接口实现而另一个则利用Servlet接口实现。
在web.xml中加入
            <listener>
               <listener-class>
                  org.springframework.web.context.ContextLoaderListener
              </listener-class>
           </listener>
或者:
         <servlet>
            <servlet-name>context</servlet-name>
            <servlet-class>
                  org.springframework.web.context.ContextLoaderServlet
            </servlet-class>
            <load-on-startup>1</load-on-startup>
         </servlet>
Web容器会自动加载WEB-INF/applicationContext.xml初始化ApplicationContext实例.如果你指定配置文件就可以通过context-param指定:
      <context-param>
         <param-name>contextConfigLocation</param-name>
         <param-value>/WEB-INF/myApplicationContext.xml</param-value>
      </context-param>
配置完成后就可以通过WebApplicationContextUtils.getWebApplicationContext方法在Web应用中获取ApplicationContext的引用.




posted on 2006-10-16 23:50 嫁蛙 阅读(445) 评论(0)  编辑  收藏 所属分类: hiberante&spring


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

常用链接

留言簿(1)

随笔分类

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜