IOC

简介

IOC是(Inversion of Control,控制反转)的简写。Spring提供IOC容器,将对象间的依赖关系交由Spring进行控制,避免硬编码所造成的的过度程序耦合。它由DI(Dependency Injection,依赖注入)来实现。

那么到底什么是Spring IOC?

IoC容器是啥?

import org.springframework.beans.BeansException;
import org.springframework.core.ResolvableType;
import org.springframework.lang.Nullable;

public interface BeanFactory {
    //前缀
    String FACTORY_BEAN_PREFIX = "&";
    // 多个 getBean 方法
    Object getBean(String var1) throws BeansException;

    <T> T getBean(String var1, Class<T> var2) throws BeansException;

    Object getBean(String var1, Object... var2) throws BeansException;

    <T> T getBean(Class<T> var1) throws BeansException;

    <T> T getBean(Class<T> var1, Object... var2) throws BeansException;

    <T> ObjectProvider<T> getBeanProvider(Class<T> var1);

    <T> ObjectProvider<T> getBeanProvider(ResolvableType var1);

    //是否包含 Bean
    boolean containsBean(String var1);

    //是否是单例
    boolean isSingleton(String var1) throws NoSuchBeanDefinitionException;

    //是否是原型
    boolean isPrototype(String var1) throws NoSuchBeanDefinitionException;

    //是否类型匹配
    boolean isTypeMatch(String var1, ResolvableType var2) throws NoSuchBeanDefinitionException;

    boolean isTypeMatch(String var1, Class<?> var2) throws NoSuchBeanDefinitionException;

    //获取Bean 类型
    @Nullable
    Class<?> getType(String var1) throws NoSuchBeanDefinitionException;

    //获取Bean别名
    String[] getAliases(String var1);
}

演示(以SpringBoot中注解方式装配Bean到Spring容器中为例)

1.首先我们定义一个简单的User对象

public class User{
    private Long id;
    private String userName;
    private String note;

    /*** getter and setter ***/
}

2.然后定义一个java的配置文件APPConfig.java

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {
    @Bean(name = "user")
    public User initUser(){
        User user = new User();
        user.setId(1L);
        user.setUserName("name");
        user.setNote("note");
        return user;
    }
}

3.做好这些 ,就可以使用 AnnotationConfigApplicationContext 来构建自己的 IoC 容器了

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class IoCTest {
    private static Logger logger = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);
    public static void main(String[] args){
        ApplicationContext ctx =
                new AnnotationConfigApplicationContext(AppConfig.class);
        User user = ctx.getBean(User.class);
        logger.info("user' id is " + user.getNote());
    }
}
02-13 05:49