Spring学习(二)spring ioc注入的三种方式

一、spring ioc注入有哪三种方式:

a  setter
    原理 : 在目标对象中,定义需要注入的依赖对象对应的属性和setter方法;“让ioc容器调用该setter方法”,将ioc容器实例化的依赖对象通过setter注入给目标对象,封装在目标对象的属性中。


b  构造器
    原理 : 为目标对象提供一个构造方法,在构造方法中添加一个依赖对象对应的参数。ioc容器解析时,实例化目标对象时会自动调用构造方法,ioc只需要为构造器中的参数进行赋值;将ioc实例化的依赖对象作为构造器的参数传入。


【接口注入
    原理 : 为依赖对象提供一个接口实现,将接口注入给目标对象,实现将接口的实现类注入的效果。比如HttpServletRequest  HttpServletResponse接口
    注意:这是ioc提供的方式,spring中的ioc技术并没有实现该种注入方式】


c  方法注入
    原理 : 在目标对象中定义一个普通的方法,将方法的返回值设置为需要注入的依赖对象类型。通过ioc容器调用该方法,将其创建的依赖对象作为方法的返回值返回给目标对象。   

二、具体实现

三种方法在实现上主要是被注入类以及applicationContext.xml不同,具体写法包括参数配置如下:
action:

package com.etoak.action;

import com.etoak.dao.UserDaoImpl;

public class LoginAction {
    /*
     * 1 setter注入   struts2表单项封装就是用了setter注入
     * 
       private UserDaoImpl ud;

       public void setUd(UserDaoImpl ud,String name) {
           this.ud = ud;
       }
    */
    /*
     * 2 构造器方式   构造器参数不固定,在xml中描述
       private UserDaoImpl ud;
       private String name;

       public LoginAction(UserDaoImpl ud,String name){
           this.ud = ud;
           this.name = name;
       }
    */
    /*
     * 3 方法注入:方法的返回值为要注入的对象类型
    */
    public UserDaoImpl etoak(){
        return null;
    }
    public void init(){
        System.out.println("loginActoin初始化了");
    }
    public String execute() throws Exception{
        etoak().login();
        /*ud.login();   
        System.out.println("name---->"+name);*/
        return "success";
    }
}

applicationContext.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"
    default-lazy-init="true">
    

    
    <bean id="action" class="com.etoak.action.LoginAction" init-method="init" lazy-init="true" scope="singleton">
        
        
        <lookup-method name="etoak" bean="dao"/> 
    bean>  
    <bean id="dao" class="com.etoak.dao.UserDaoImpl">bean>
beans>







你可能感兴趣的:(spring,spring框架从零开始)