Spring IOC

 

Spring IOC

 

--------------------------------------------------------------------------------------------------------------------------
IOC控制反转

IOC是DI的原理。依赖注入是向某个类或方法注入一个值,其中所用到的原理就是控制反转。Spring容器的初始化和加载的原理
--------------------------------------------------------------------------------------------------------------------------


<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.3.11.RELEASE</version>
    </dependency>
</dependencies>

// application-context.xml
<bean id="testBeanService" class="com.zack.demo.TestBeanServiceImpl"/>


public class TestBeanServiceImpl implements TestBeanService {
    public String getMessage() {
        return "a test bean";
    }
}

// ApplicationContext 是个接口
public static void main(String[] args) {
    // 加载xml配置
    ApplicationContext context = 
        new ClassPathXmlApplicationContext("classpath:application.xml");

    // IOC获取Bean
    TestBeanService testBeanService = context.getBean(TestBeanService.class)
}


// 初始化IOC容器
ClassPathXmlApplicationContext implements ApplicationContext
    refresh() //  刷新了整个context,加载所有Bean定义,创建对应的单例
        loadBeanDefinitions(); // 加载Bean的定义。实现交给了子类

// 依赖注入
context.getBean(TestBeanService.class)

 

参考URL   https://www.jianshu.com/p/7b1746a86faf

 

posted @ 2019-05-31 09:06  webglcn  阅读(103)  评论(0编辑  收藏  举报