Spring Boot 注解 ---- @Component


前言

在Spring Boot中,各种各样的Bean都是交由Spring Boot进行管理,其中有一个比较特殊的Bean —— Component,名为组件。通过扫描类路径加载到容器中。

作用

@Component注解表明一个类会作为组件类,并告知Spring要为这个类创建bean。
Bean和Component的区别

  • 相同点
    • 两者的结果都是为Spring容器注入Bean
  • 不同点
    • @Component通常是通过类路径扫描来侦测以及自动装配Bean到Spring容器中
    • @Bean 注解通常是我们在标有该注解的方法中定义产生这个Bean的逻辑

父子注解及解释

@Component是一个父注解,其下派生了许多子注解
其中比较常用的有:

  • @Configuration:标注这个类为配置类
  • @Repository:标注这个类为持久层
  • @Service:标注这个类为服务层
  • @Controller:标注这个类为控制层

使用方法

/**
 * 创建组件类
 */
@Component
public class Car {
    private String bread = "BYD";
    private Integer price = 0;


    public String getBread() {
        return bread;
    }

    public void setBread(String bread) {
        this.bread = bread;
    }

    public Integer getPrice() {
        return price;
    }

    public void setPrice(Integer price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Car{" +
                "bread='" + bread + '\'' +
                ", price=" + price +
                '}';
    }
}

/**
 * 引用方法
 * 此处两个引用方法均按照Spring官方的规范编写
 */
public class Test {
    /**
     * 引用方法1
     */
    @Resource
	private Car car;

    /**
     * 引用方法2:去掉上面@Resource注解
     */
    @Autowired
    public Test(Car car) {
    	this.car = car;
    }
}

源码解析

注解源码分析

/**
 * 表示带注释的类是“组件”。在使用基于注释的配置和类路径扫描时,
 * 此类类被视为自动检测的候选对象。其他类级别的注释也可以被视为标识
 * 组件,通常是一种特殊类型的组件,例如:
 *  @Repository注释或AspectJ的@Aspect注释。
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Indexed
public @interface Component {

	/**
	 * 指定当前Bean的名称,在引入的时候根据bean的名称引入即可
	 */
	String value() default "";

}

@Component的注释上也说了他的作用 :

在使用基于注释的配置和类路径扫描时,此类类被视为自动检测的候选对象。

这句话的意思是,在SpringBoot启动的时候,会通过扫描当前包下所有注释@Component的类,将他们实例化注入到Spring容器中。
那他是怎么扫描并注入组件的,下面看一下过程解析

流程解析

未完待续。。。。。。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM