在 Spring 中,ClasspathApplicationContext
是一个用于从类路径中加载和刷新应用程序上下文的实现。要重用 ClasspathApplicationContext
,可以采用以下方法:
ClasspathApplicationContext
用作独立应用程序的基类。import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyApplication {
private ApplicationContext context;
public MyApplication() {
context = new ClassPathXmlApplicationContext("applicationContext.xml");
}
public void run() {
// 在此处编写应用程序逻辑
}
public static void main(String[] args) {
MyApplication app = new MyApplication();
app.run();
}
}
getBean()
方法从上下文中获取所需的 bean。MyService service = (MyService) context.getBean("myService");
refresh()
方法刷新上下文。context.refresh();
registerShutdownHook()
方法注册关闭钩子,以便在应用程序退出时正确关闭上下文。context.registerShutdownHook();
close()
方法关闭上下文。context.close();
通过以上方法,可以在独立应用程序中重用 ClasspathApplicationContext
。
没有搜到相关的文章