在应用程序完成之后,我想关闭 Spring 上下文。 相关代码有一个 ApplicationContext引用,但我找不到一个 close方法。
ApplicationContext
close
Downcast your ApplicationContext to ConfigurableApplicationContext which defines close() method:
ConfigurableApplicationContext
close()
((ConfigurableApplicationContext)appCtx).close();
You need to register a shutdown hook with the JVM as shown below:
((AbstractApplicationContext)appCtx).registerShutdownHook();
For more information see: Spring Manual: 3.6.1.6 Shutting down the Spring IoC container gracefully in non-web applications
If you initialise context like one below
ApplicationContext context = new ClassPathXmlApplicationContext(beansXML);
clean context like these
((ClassPathXmlApplicationContext) context).close();
If Java SE 7 and later, don't close, use try-with-resources which ensures that each resource is closed at the end of the statement.
try(final AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[]{"classpath*:META-INF/spring/*.xml" })) { //write your code }
Steps to close the ApplicationContext Object
example:
ApplicationContext context = new ClassPathXmlApplicationContext("mybeans.xml"); ((ConfigurableApplicationContext)context ).close();
public static void main(String[] args) { ApplicationContext context=new ClassPathXmlApplicationContext("SpringCnf.xml"); Resturant rstro1=(Resturant)context.getBean("resturantBean"); rstro1.setWelcome("hello user"); rstro1.welcomeNote(); ((ClassPathXmlApplicationContext) context).close();
Even a more simpler way of doing this is using the abstract implementation of the ApplicationContextinterface.
ApplicationContextinterface
AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); context.close();