springboot是如何实现自动配置,加载生成bean,这篇告诉你

1.首先你得知道springbootApplication这个注解的作用,它是一个复合注解
@SpringBootApplication 看作是 @Configuration、@EnableAutoConfiguration、@ComponentScan 注解的集合。

@EnableAutoConfiguration:启用 SpringBoot 的自动配置机制
@ComponentScan: 扫描被@Component (@Service,@Controller)注解的bean,注解默认会扫描该类所在的包下所有的类。
@Configuration:允许在上下文中注册额外的bean或导入其他配置类
2.下来它将访问是否存在application.proporites文件,找到后加载里面的配置信息,并且生成bean,比如加载到redis配置,它将生成redisTemplate类,并将它注入
3.spring加载bean的过程是什么呢

  1. Bean 容器找到配置文件中 Spring Bean 的定义。 Bean 容器利用 Java Reflection API

  2. 创建一个Bean的实例。 如果涉及到一些属性值 利用 set()方法设置一些属性值。 如果 Bean 实现了 BeanNameAware
    接口,调用 setBeanName()方法,传入Bean的名字。 如果 Bean 实现了 BeanClassLoaderAware
    接口,调用 setBeanClassLoader()方法,传入 ClassLoader对象的实例。 与上面的类似,如果实现了其他
    *.Aware接口,就调用相应的方法。

  3. 如果有和加载这个 Bean 的 Spring 容器相关的 BeanPostProcessor
    对象,执行postProcessBeforeInitialization() 方法

  4. 如果Bean实现了InitializingBean接口,执行afterPropertiesSet()方法。

  5. 如果 Bean
    在配置文件中的定义包含 init-method 属性,执行指定的方法。

  6. 如果有和加载这个 Bean的 Spring 容器相关的
    BeanPostProcessor 对象,执行postProcessAfterInitialization() 方法 当要销毁 Bean
    的时候,如果 Bean 实现了 DisposableBean 接口,执行 destroy() 方法。 当要销毁 Bean 的时候,如果
    Bean 在配置文件中的定义包含 destroy-method 属性,执行指定的方法。

4.这时候springboot已经实现了自动配置功能,你将只需要少量的配置即可完成开发。

java学习交流github地址:https://github.com/lx-IT-P/

**

关注公众号免费领取技术书籍和面试资料

在这里插入图片描述

**

猜你喜欢

转载自blog.csdn.net/weixin_44302240/article/details/103952124