Reputation: 572
I'm learning spring and I got confused in init, destroy method and constructor part
This is spring-config.xml
<bean id="msgBean" class="com.example1.MessagesBean" init-method="start">
</bean>
<bean name="carBean" class="com.example2.Car" init-method="initEngine">
<constructor-arg ref="engineBean" />
</bean>
<bean id="engineBean" class="com.example2.Engine" />
This is Car.java
public class Car {
private Engine engine;
public Car(Engine engine){
System.out.println("Inside Car constructor");
this.engine = engine;
}
public void startCarEngine(){
engine.startEngine();
}
private void initEngine(){
System.out.println("heating up engine");
}
}
This is Engine.java
public class Engine {
public Engine(){
System.out.println("Inside Engine constructor");
}
public void startEngine(){
System.out.println("Engine is starting...");
}
}
This is MessageBean.java
public class MessagesBean {
private static final String HELLO_WORLD = "Hello World";
public MessagesBean(){
System.out.println("Printing " + HELLO_WORLD);
}
public void start(){
System.out.println("Step 2.Bean is starting");
}
}
This is my Main class
AbstractApplicationContext abstractAppContext = new ClassPathXmlApplicationContext("spring-config.xml");
MessagesBean msgBean2 = abstractAppContext.getBean("msgBean", MessagesBean.class);
This is my output
Printing Hello World
Step 2.Bean is starting
Inside Engine constructor
Inside Car constructor
heating up engine
My question is I called only MessageBean
in my main class and it's supposed to call only MessageBean Constructor
and init
method but why two other beans constructors and init method are called or did I do something wrong? What if I have different init, destroy methods for different beans and I only want to initialize/call specific bean(s) constructors and init methods ?
Upvotes: 0
Views: 1287
Reputation: 240898
by default spring beans gets eagerly initialized, if you want them to initialize lazily add this property in bean definition
lazy-init="true"
Upvotes: 2