还不懂「ioc」?

664 阅读2分钟

这是我参与8月更文挑战的第22天,活动详情查看:8月更文挑战

IOC容器

  • ioc容器之所以叫容器,就是容纳了管理Bean的容器
  • 所有的ioc容器必须要实现BeanFactory接口 BeanFactory源码
package org.springframework.beans.factory;  
import org.springframework.beans.BeansException;  
public interface BeanFactory {  
    String FACTORY_BEAN_PREFIX = "&";
    // getBean的各种方法
    Object getBean(String name) throws BeansException;  
    <T> T getBean(String name, Class<T> requiredType) throws BeansException;  
    <T> T getBean(Class<T> requiredType) throws BeansException;  
    Object getBean(String name, Object... args) throws BeansException; 
    // 是否包含Bean
    boolean containsBean(String name);  
    // Bean是否为单例
    boolean isSingleton(String name) throws NoSuchBeanDefinitionException;  
    // Bean是否为原型
    boolean isPrototype(String name) throws NoSuchBeanDefinitionException; 
    // 是否类型匹配
    boolean isTypeMatch(String name, Class<?> targetType) throws NoSuchBeanDefinitionException; 
    // 获取Bean类型
    Class<?> getType(String name) throws NoSuchBeanDefinitionException;  
    // 获取Bean 别名
    String[] getAliases(String name);  
}
  • 我们可以看到各种类型的getBean,在ioc容器中,可以按照类型或者名称去获取Bean
  • 在默认情况下,Bean都是单例的,所以在getBean返回的时候都是同一个对象,这里面就用到了isSingleton

图片.png

springboot的装配与获取Bean

  • 先创建实体类(POJO-stu)

图片.png

  • 配置文件

图片.png

  • 其中@Bean就是在配置文件下,IOC会根据此注解来生成ioc容器装配Bean
  • @Bean就是代表将initStu这个方法的返回值(POJO的stu)装配到ioc容器中

  • 在完成以上的操作以后我们就可以使用AnnotationConfigApplicationContext
  • 可以ApplicationContext t = new AnnotationConfigAppl丰cationContext(AppConfig . class);
  • stu s = t.getBean(stu.class)去获取到stu的bean

子弟鞥已装配Bean

  • 在开发过程中,我们不会去每个都使用Bean注解注入到Spring的ioc容器中
  • 那么Spring是通过扫描进行装配,使用的注解是@Component和@ComponentScan
  • @Component可以去标明哪个类可以被扫描进入spring的ioc容器中
  • @ComponentScan可以直接标明采用什么策略去扫描装配Bean

ComponentScan

  • 在上面的POJO的stu上方加入@Component来表明这个类将被Sring IOC容器扫描装配
  • 在ApplicationConfig上方加入@ComponentScan注解,用来扫描,只能扫当前的ApplicationConfig包
  • 其实我们可以自定义扫描的位置,来看ComponentScan注解的源码

图片.png

  • 其中AliasFor就是可以定义扫描的包

  • basePackxxx 可以定义扫描的包

  • nameGenerator 是Bean name 生成器

  • scopeResolver 作用域代理模式

  • includeFilters 当满足过滤器的条件时扫描

  • excludeFilters 当不满足过滤器的条件时扫描

  • 通过配置项basePackages用来扫描包名

  • 只要带有xxxFileter的就是定义满足过滤器的条件的Bena才去扫描