Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when is a spring bean instantiated

Tags:

java

spring

ApplicationContext ctx = new ClassPathXmlApplicationContext(     "com/springinaction/springidol/spring-idol.xml"); Performer performer = (Performer) ctx.getBean("duke"); performer.perform(); 

In the above, when are the beans instantiated, when the ApplicationContext is created or when the getBean() is called?

like image 436
java_geek Avatar asked Dec 15 '10 19:12

java_geek


People also ask

How Bean is instantiated in Spring?

Bean life cycle is managed by the spring container. When we run the program then, first of all, the spring container gets started. After that, the container creates the instance of a bean as per the request, and then dependencies are injected. And finally, the bean is destroyed when the spring container is closed.

What is an initialization method and how is it declared on a Spring bean?

init-method is the attribute of the spring <bean> tag. It is utilized to declare a custom method for the bean that will act as the bean initialization method. We can define it as follows. Here myPostConstruct() method is the bean initialization method in the Student class.

Who creates an instance of Spring bean?

To put it another way, when you define a bean definition and it is scoped as a singleton, then the Spring IoC container will create exactly one instance of the object defined by that bean definition.

How does @bean works in Spring?

Spring @Bean Annotation is applied on a method to specify that it returns a bean to be managed by Spring context. Spring Bean annotation is usually declared in Configuration classes methods. In this case, bean methods may reference other @Bean methods in the same class by calling them directly.


2 Answers

Assuming the bean is a singleton, and isn't configured for lazy initialisation, then it's created when the context is started up. getBean() just fishes it out.

Lazy-init beans will only be initialised when first referenced, but this is not the default. Scoped beans (e.g. prototype-scoped) will also only be created when first referenced.

like image 109
skaffman Avatar answered Sep 28 '22 07:09

skaffman


According to Spring documentation,

The default behavior for ApplicationContext implementations is to eagerly pre-instantiate all singleton beans at startup.

Also, you can set them to load lazily.

like image 24
vstoyanov Avatar answered Sep 28 '22 07:09

vstoyanov