Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Component @Scope("singleton") public class BootStrapper implements ApplicationListener<ContextStartedEvent> {

I am trying to do a one time initialization of my webapp. I need a singleton for the ApplicationListener class, so I set the scope to Singleton, but it is creating multiple instances. This BootStrapper is not defined in any other xml config files. I know that the default scope is singleton, but had to add @Scope("singleton") because it was not a singleton. Even with this annotation, it still creates multiple instances. Here is my ApplicationListener.

@Component
@Scope("singleton")
public class BootStrapper implements ApplicationListener<ContextRefreshedEvent> {

Am I missing anything?

like image 265
Chandana Sapparapu Avatar asked Mar 07 '13 12:03

Chandana Sapparapu


People also ask

Is @component class Singleton?

Yes, that is correct, @Component is a Spring bean and a Singleton. 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).

What is the scope of @component in Spring?

@Component is an annotation that allows Spring to automatically detect our custom beans. In other words, without having to write any explicit code, Spring will: Scan our application for classes annotated with @Component. Instantiate them and inject any specified dependencies into them.

What is Spring component annotation?

Spring Component annotation is used to denote a class as Component. It means that Spring framework will autodetect these classes for dependency injection when annotation-based configuration and classpath scanning is used.


1 Answers

To have a callback that is invoked after the bean is initialized, use @PostConstruct.

@Component
public class BootStrapper() {

     @PostConstruct
     public void doSomething() {
          System.out.println("I am initalized!");
     }
}
like image 60
Ralph Avatar answered Nov 14 '22 15:11

Ralph