Spring Boot注解全攻略(三):@Component

2,387 阅读1分钟

前言

从前面我们知道,所谓的Bean其实就是一个个对象;但是@Bean注解是标注在方法上的,意思就是通过方法返回一个对象,那么有没有直接通过类获取对象的呢?当然有,那就是@Component,被该注解标注的类会被注册到当前容器,bean的id就是类名转换为小驼峰。

源码

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Indexed
public @interface Component {
    String value() default "";
}

使用

直接标注在类上,Spring扫描时会将其加入容器。

@Component // or @Component("myBean")
public class MyClass {
    // write your bean here...
}

Spring常用注册Bean注解:

  • @Component, @Service, @Repository, @Controller四个注解作用于类上,实质上是一样的,注册类到当前容器,value属性就是BeanName
  • @Configuration注解也作用于类上,该注解通常与@Bean配合使用,注册方法返回类型作为对象,用作配置。
  • @Bean用于方法上,该方法需要在@Configutation标注的类里面,且方法必须为public

补充说明

@Component注解的效果与@Bean的效果类似,也是单例模式。可以搭配的注解也类似,例如@Scope, @Profile, @Primary等等。