spring 之IOC

IOC:控制反转。

理解:谁控制谁,控制什么?为什么是反转。

控制什么:控制对象的创建与销毁,以及文件资源的获取。

谁控制谁:传统javase,对象由new创建对象,程序主动创建依赖对象。而spring中,是直接交给IOC容器来创建。

为何是反转:传统中有对象主动获取依赖对象,即正转。反转则是有容器来帮忙创建及注入依赖对象,对象只是被动接受依赖对象。

IOC 为什么需要:

解决了依赖对象的高耦合,随时可通过配置解决各种依赖。

设计原则:工厂模式。

bean = factory.getbean("beanName");

提供一个0注解配置IOC。

package com.mobile263.service.impl;

import com.mobile263.dao.CustomerDao;
import com.mobile263.service.CustomerService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service(value = "customerService")
public class CustomerServiceImpl implements CustomerService {

    @Resource
    private CustomerDao customerDao;

    @Override
    public void save() {
        customerDao.save();
    }
}
package com.mobile263.test;

import com.mobile263.config.SpringConfig;
import com.mobile263.dao.CustomerDao;
import com.mobile263.service.CustomerService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringConfig.class})
public class SpringIocTest {

    @Resource(name="customerDao")
    private CustomerDao customerDao;

    @Resource(name="customerService")
    private CustomerService customerService;

    @Value("${jdbcUrl}")
    private String url;

    @Test
    public void test1(){
        System.out.println(customerDao);
    }

    @Test
    public void test2(){
        customerService.save();
    }

    @Test
    public void test3(){
        System.out.println(url);
    }
}

具体可参考:https://github.com/chen-liang-ying/spring-ioc.git

猜你喜欢

转载自blog.csdn.net/yingcly003/article/details/84935698