在我的Spring應用程序中,我注意到了Spring(或Eclipse)的奇怪行爲。它讓我困惑。用try/catch包圍的ApplicationContext確定在finally塊中完成後關閉。但在Eclipse控制檯中,我看到它在bean調用之前關閉。在調用bean之前關閉Spring ApplicationContext
public class Main {
public static void main(String[] args) {
ApplicationContext context = null;
try {
context = new ClassPathXmlApplicationContext(new String[] { "beans-annot.xml" });
Launcher launcher = (Launcher) context.getBean("launcher");
System.out.println(launcher);
launcher.invokeBean();
} catch (BeansException e) {
e.printStackTrace();
} finally {
if(context != null)
((AbstractApplicationContext) context).close();
}
}
}
@Component
public class Bean {
public void invoke(){
System.out.println("invoke bean");
}
}
@Component
public class Launcher {
@Autowired
public Bean bean;
//setter
public void invokeBean(){
bean.invoke();
}
}
豆-annot.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" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="my.ioc" />
<context:annotation-config />
</beans>
在Eclipse控制檯輸出:
[INFO] --- exec-maven-plugin:1.2.1:java (default-cli) @ IoC ---
окт 30, 2014 8:52:56 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org[email protected]6e4e4adb: startup date [Thu Oct 30 20:52:56 FET 2014]; root of context hierarchy
окт 30, 2014 8:52:56 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans-annot.xml]
[email protected]
окт 30, 2014 8:52:56 PM org.springframework.context.support.ClassPathXmlApplicationContext doClose
INFO: Closing org[email protected]6e4e4adb: startup date [Thu Oct 30 20:52:56 FET 2014]; root of context hierarchy
invoke bean
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
正如你可以看到doClose方法初始化bean之前,爲什麼呢?我認爲這是Eclipse或Maven插件錯誤...項目是用exec-maven-plugin構建的。
你可以發佈'beans-annot.xml'文件嗎? – 2014-10-30 18:24:49
'System.out.println(launcher);'已經執行,這就是爲什麼你可以看到'my.ioc.Launcher @ 2b7f535d' – 2014-10-30 18:26:10
但我不知道爲什麼'launcher.invokeBean();'不顯示任何內容在控制檯 – 2014-10-30 18:27:13