What does the @Component annotation do?

Asked

Viewed 7,668 times

6

What Spring actually does when we write it down @Component in a class? How does it work "underneath the scenes"

  • Related question: http://answall.com/a/139/227

  • Related article :) http://luizricardo.org/2014/03/quais-annotations-usar-nos-componentes-do-spring-3/

2 answers

8

Spring supports the annotation @Component since his version 2.5, and it serves to indicate to the framework that that class is a bean which should be administered by the implementation of Ioc Container spring.

As Weslley Tavares commented, the note @Component is a stereotype, and his specializations are @Repository, @Service and @Controller.

When a class is marked with @Component means that it will use the depletion injection pattern, and will be eligible for auto-configuration and auto-detection of Beans annotated from scanning of classpath that the Spring Ioc Container does.

When loading the application, Spring scans the classpath behind classes annotated with @Component or specializations to then create an instance with the type scope Singleton by default, i.e., the Beans sane stateless (should not save status), so there is no need for a new bean instance each time there is a reference.

Spring will only scan Beans eligible you specify in the file applicationContext.xml, thus:

<context:component-scan base-package="com.path.dos.beans" />

Practical use

The annotation @Component should be used at class level, thus:

@Component
public class Foo {
//implementação da  classe
}

To reference it in another context (get the instance), you can use the annotation @Autowired, thus:

@Component
public class Bar {
   @Autowired
   private Foo foo;
}
  • Or, if using a bean outside of a @Component, should use the annotation @SpringBean, nay @Autowired.

  • Gustavo Cinque, the annotation @SpringBean is part of the Apache Wicket framework, which supports spring Beans injection, and requires importing the dependency. Another way to use the bean without @Autowired would be doing the manual injection of the class that will use this bean in the context of injection of spring into the code, placing this line in the constructor of the class: SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);

  • Is it real? I always use Wicket, that’s why I confused :/

4


According to the own definition of creators, it represents a component (bean) which is detected automatically when working with Annotations-based settings and searching for class paths.

Other elements, such as @Repository, @Service and @Controller, are some stereotypes that implement the @Component. This way, you can create another specialization of @Component according to your need.

Example:

@Component
@Scope("prototype")
public @interface MinhaClasse{
...
}

Thus, we have a new specialization of @Component.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.