Spring学习第二天:IOC,DI

IOC:inverse of control 控制反转

DI:Dependency inject 依赖注入

解释:高层模块(控制层)不应该依赖你低层模块,两者都应该依赖其抽象。server不需要知道具体的实现,只需要知道接口(面向接口编程)。可以通过配置文件,知道具体的实现。

示例代码:

接口代码:

 

package test04.dao;

public interface IUserDao {
    public void sayHello();
}

 

dao代码:

 

package test04.dao;


public class UserDao implements IUserDao {

    public void sayHello() {
        System.out.println("hello---------------");
    }
}

 

xml代码:

 

<bean id="userdao" class="test04.dao.UserDao"></bean>
<bean id="service" class="test04.service.UserService">
     <property name="iUserDao" ref="userdao"></property>
</bean>

 

Main代码:

 

public class Main {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classBeanMVC.xml");
        UserService userService = (UserService) applicationContext.getBean("service");
        userService.test();
    }
}

 

posted @ 2018-01-16 10:25  梁宝谊  阅读(107)  评论(0编辑  收藏  举报