preface

As we know, beans are just objects; But the @bean annotation is annotated on a method, meaning that an object is returned by a method. Is there any way to get an object directly from a class? There is, of course, @Component. The class marked by this annotation will be registered with the current container, and the bean ID will be converted to the little hump.

The source code

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

use

Annotated directly on the class, Spring will add it to the container when it scans.

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

Spring commonly uses registered Bean annotations:

  • @Component.@Service.@Repository.@ControllerThe four annotations applied to the class are essentially the same: register the class to the current container, and the value property is BeanName
  • @ConfigurationAnnotations also apply to classes, which are usually associated with@BeanIn conjunction, the registration method returns a type as an object, which is used for configuration.
  • @BeanFor methods that need to be used in@ConfigutationClass, and the method must be public

added

The effect of the @Component annotation is similar to the effect of the @Bean singleton. Similar annotations can be used, such as @scope, @profile, @primary, and so on.