Alan Evangelista
Alan Evangelista

Reputation: 3163

Spring: @Component

Spring documentation defines @Component annotation in the following way: "Indicates that an annotated class is a "component". Such classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning. "

This is concise, but it does not say a lot. I understand that @Component is used to indicate that a class lifecycle (creation/destruction) will be managed by Spring. The question I have: I need to use it only in classes that will be autowired somewhere (1) or do I also need to use it in classes that have autowired attributes (2)?

(1)

@Component
class B {
}

class A {

   // @Autowired
   B b;
}

(2)

@Component
class B {
}

@Component
class A {

  // @Autowired
  B b;
}

Upvotes: 2

Views: 4921

Answers (1)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340733

Well, strictly speaking you don't have to use anywhere, you can define beans in XML like in the old days. Also you can use @Service or @Repository like in the old days. But back to your question:

If your bean A is not annotated with @Component or otherwise known to the Spring context, it will never be created and managed by Spring. So you either have to use an annotation or define A in XML.

This is true for B as well. If you want it to be a subject for autowiring, it must be known to Spring - either by annotation scanning or by XML.

At the end of the day it doesn't really matter whether you use XML, annotation or Java configuration. It's important that both beans are known to application context.

Upvotes: 6

Related Questions