spring源码解析——@Component注解原理


一、@Component作用

@Component是用在类上面的注解,它的功能是用来告诉spring当前类是一个Bean对象,然后让spring对该类进行自动创建并管理。

二、@Component注解实现的原理

@Component注解底层主要依赖于一个叫做includeFilters的对象来实现的。该对象其实是spring扫描器中的一个属性,它规定了哪些对象会被spring容器识别。所以如果一个对象如果不加上@Component注解,但是在扫描注解上加上该类的名称,那么这个类也会呗spring容器识别成一个对象纳入自身的管理范围,注解代码如下:

@ComponentScan(value = "com.muyichen",
	includeFilters = {
    
    
		@ComponentScanFilter(
			type = FilterType.ASSIGNABLE_TYPE,
			classes = ProductService.class
		)
	}
)
public class AppConfig {
    
    }

如上方的代码,如果在spring容器加载的属性配置类上方,添加上这个注解,那么就可以把没有@Component注解的ProductService.class类加入到spring容器中了。

总结一下:

当spring启动的时候,扫描器会通过ASM将target目录下所有的class文件的元数据读取出来,然后在扫描的过程中会给自身的includeFilters属性添加上一个默认的类,这个类就是@Component注解类。之后的扫描过程就是将对应拥有@Component注解的class文件加载成一个个的Bean对象放入到spring容器中进行管理。

猜你喜欢

转载自blog.csdn.net/qq_42697271/article/details/120866660