Answer the question
In order to leave comments, you need to log in
What is the bean initialization process?
Hello everyone,
There was a question about the bean initialization process. I’ll immediately begin to describe on my fingers, otherwise I’m afraid I will describe indistinctly.
So we have the HelloWorld class:
public class HelloWorld {
private String message;
// getter and setter go here
public void init() {
this.setMessage("null");
System.out.println("Bean is going through init.");
}
public void destroy() {
System.out.println("Bean will destroy now.");
}
}
public class MainApp {
public static void main(String[] args) {
AbstractApplicationContext context =
new ClassPathXmlApplicationContext("/spring/BeanLifeCycle/Beans.xml");
HelloWorld obj = (HelloWorld) context.getBean("hello");
System.out.println(obj.getMessage());
context.registerShutdownHook();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="hello"
class="spring.BeanLifeCycle.HelloWorld"
init-method="init"
destroy-method="destroy">
<property name="message" value="Property value of message"></property>
</bean>
</beans>
Pro 02, 2015 12:23:14 DOP. org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org[email protected]2b71fc7e: startup date [Wed Dec 02 00:23:14 CET 2015]; root of context hierarchy
Pro 02, 2015 12:23:14 DOP. org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring/BeanLifeCycle/Beans.xml]
Bean is going through init.
Pro 02, 2015 12:23:14 DOP. org.springframework.context.support.ClassPathXmlApplicationContext doClose
INFO: Closing org[email protected]2b71fc7e: startup date [Wed Dec 02 00:23:14 CET 2015]; root of context hierarchy
null
Bean will destroy now.
Answer the question
In order to leave comments, you need to log in
Метод, указанный в init-method вызывается сразу после создания экземпляра. Тем самым Вы заменяете значение message на "null".
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question