【Spring】IOC

参考:

阿里开发者-Spring循环依赖那些事(有完整流程图)   https://mp.weixin.qq.com/s/cqkZEvmmh7jnNt2K5r_lXg   

 

The org.springframework.beans and org.springframework.context packages are the basis for Spring Framework’s IoC container.

BeanFactory interface provides an advanced configuration mechanism capable of managing any type of object.

ApplicationContext is a sub-interface of BeanFactory. It adds:

  • Easier integration with Spring’s AOP features
  • Message resource handling (for use in internationalization)
  • Event publication
  • Application-layer specific contexts such as the WebApplicationContext for use in web applications.

 

ApplicationContext represents the Spring IoC container and is responsible for instantiating, configuring, and assembling the beans.
The configuration metadata is represented in XML, Java annotations, or Java code.
传统格式:ClassPathXmlApplicationContext or FileSystemXmlApplicationContext.
web应用场景:web.xml

 定义源数据

  • Annotation-based configuration: define beans using annotation-based configuration metadata.
  • Java-based configuration: define beans external to your application classes by using Java rather than XML files. To use these features, see the @Configuration, @Bean, @Import, and @DependsOn annotations.

 

 


 

循环依赖

问题:

1、什么是循环依赖?
2、为什么会产生循环依赖?
3、循环依赖有哪些场景?
4、Spring如何解决循环依赖的?
5、Spring为什么使用三级缓存?
6、Spring支持AOP循环依赖,为何还存在循环依赖异常?
7、Spring不支持的循环依赖场景及如何解决?

 

循环依赖:A->B->C->A

解决关键词:三级缓存

核心代码:org.springframework.beans.factory.support.DefaultSingletonBeanRegistry

  • private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);:  单例对象缓存池,beanName->Bean,其中存储的就是实例化,属性赋值成功之后的单例对象
  • private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);:                 早期的单例对象,beanName->Bean,其中存储的是实例化之后,属性未赋值的单例对象。
  • private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);:     单例工厂的缓存,beanName->ObjectFactory

核心概念:

BeanDefinition:spring核心bean的配置信息
Spring Bean:spring管理的已经初始化好以后的可使用的实例
首先,通过spring通过扫描各种注解 @Compoent、@Service、@Configuration等等把需要交给spring管理的bean初始化成 BeanDefinition 的列表
然后,根据 BeanDefinition 创建spring bean的实例
Java Bean:Java简单通过构造函数创建的对象
Spring通过推断构造方法后,通过反射调用构造函数创建的对象

 

 

 

 

posted @ 2023-05-08 19:55  飞翔在天  阅读(24)  评论(0编辑  收藏  举报