144

Being fairly new to Spring I have a question about annotating a class. When annotating a class with @Component does this mean this class will be a Spring Bean and by default a singleton?

giannis christofakis
  • 8,201
  • 4
  • 54
  • 65
Marco
  • 15,101
  • 33
  • 107
  • 174

2 Answers2

176

Yes, that is correct, @Component is a Spring bean and a Singleton.

If the class belongs to the service layer you may want to annotate it with @Service instead

But have in mind that in order for these annotations to be detected, you need to place this line in applicationContext.xml:

<context:component-scan base-package="com.yourcompany" />

About singletons - spring beans are all in singleton scope by default. The only thing you have to have in mind is that you should not store state in field variables (they should only hold dependencies). Thus your application will be thread-safe, and you won't require a new instance of a bean each time. In other words, your beans are stateless.

rogerdpack
  • 62,887
  • 36
  • 269
  • 388
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 1
    When using the @Component and or @Service annotations etc.. means that i am creating Singletons, will i not run into concurrency issues? To my newbie idea it will results in a bean that is used throughout the ApplicationContext, so concurrent users will get a reference to the single bean. Or am i missing something? – Marco May 06 '11 at 07:18
  • 3
    @Marco if you don't have any state (instance variables different from spring beans), then no concurrency issues will occur. – Bozho May 06 '11 at 08:35
  • you "want" require a new instance of a bean each time or you "wont" require a new instance of a bean each time? – Harshana Jan 20 '16 at 11:51
  • @Bozho What do you mean by: "and you won't require a new instance of a bean each time"? Do mean that Spring won't have to create a new instance or you as a developer won't need to create a new instance? – user1766169 Mar 29 '17 at 08:02
39

By default - Yes.

However, you can override this behavior using the @Scope annotation. For example: @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)

Cristian Ramon-Cortes
  • 1,838
  • 1
  • 19
  • 32
Lea Zus
  • 499
  • 4
  • 2