CSmith
@CSmith
Студент.

Каков процесс инициализации bean?

Всем привет,
Возник вопрос о процессе инициализации бина. Сразу начну описывать на пальцах, а то боюсь невнятно опишу.
Значит есть у нас класс HelloWorld:
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.");
	}

}


Есть класс с main:
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();
	}

}


И, конечно же, конфигурация бинов в Beans.xml:
<?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>


Вопрос: Почему на экран выводится не "Property value of message" (значение из бина), а "null" (значение из метода init). Ведь, как я понимаю, сначала проходит инициальзация бина, потом его использование и логический конец - уничтожение. Я ожидал, что переменная message будет сначала ровняться "null" а потом станет значением из бина. Но с этими ожиданиями как всегда...
Где я лажанул?

Вывод с консоли:
Pro 02, 2015 12:23:14 DOP. org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@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.springframework.context.support.ClassPathXmlApplicationContext@2b71fc7e: startup date [Wed Dec 02 00:23:14 CET 2015]; root of context hierarchy
null
Bean will destroy now.
  • Вопрос задан
  • 861 просмотр
Решения вопроса 1
eastywest
@eastywest
Backend developer
Метод, указанный в init-method вызывается сразу после создания экземпляра. Тем самым Вы заменяете значение message на "null".
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы