1. 程式人生 > >IOC(控制反轉,反向控制)

IOC(控制反轉,反向控制)

IOC又稱DI(依賴注入),是對傳統流程的一種顛覆。當某個例項需要另一個例項協助時,在傳統的程式設計中,通常由呼叫者建立被呼叫者的例項。但在IOC中,建立被呼叫者的工作不再由呼叫者來完成,而是由容器來完成(例如Spring),而不再是呼叫者,所以說控制被反轉了,稱為控制反轉。

1、傳統設計
(1)應用層:
package xie.ioc;
public class App {

        public static void main(String[] args) {
            String name = "hello word";
            Service service = new Service();
            service.service(name);

        }
}

(2)、Service層
package xie.ioc;

public class Service {

    private Dao dao = new Dao();
    public void service(String words){
        dao.say(words);
    }
}

(3)、DAO層
package xie.ioc;

public class Dao {

    public void say(String words){
        System.out.println(words);
    }

}

2、控制反轉
(1)、IDao

package xie.ioc1;

public interface IDao {

    public String say(String words);

}

(2)、DaoImpl

package xie.ioc1;

public class DaoImpl implements IDao{

    public String say(String words) {
        // TODO Auto-generated method stub
        return words;
    }

}

(3)、IService

package xie.ioc1;

public interface IService {

    public void service(String words);

}

(4)、ServiceImpl

package xie.ioc1;

public class ServiceImpl implements IService {

    private IDao dao;

    public void service(String words) {
        // TODO Auto-generated method stub
        System.out.println(dao.say(words));
    }

    public IDao getDao() {
        return dao;
    }

    public void setDao(IDao dao) {
        this.dao = dao;
    }

}

(5)、Test

package xie.ioc1;

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

public class Test {

    public static void main(String[] args) {
        String words = "hello world";
        XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
        IService service = (IService) factory.getBean("service");
        service.service(words);
    }

}

(6)、applicationContext.xml