只是在@Solitirios 回答中添加几件事:
你忘了提几个上下文:
- GenericApplicationContext
- GenericXmlApplicationContext
- AnnotationConfigApplicationContext
- GenericWebApplicationContext
- StaticWebApplicationContext
还有很多其他的。
一般来说,GenericApplicationContext 与StaticApplicationContext 几乎相同,它们之间的唯一区别在于MessageSource 支持StaticApplicationContext。这两个类的目的是用于带有几个 bean 的小型应用程序上下文的小型测试。
GenericWebApplicationContext 和StaticWebApplicationContext 也很相似,通常用于模拟 Servlet 容器,例如测试或非 Servlet 环境。
F.e.你可以在你的代码中使用这样的东西(例如测试):
//create parent context
ApplicationContext xmlContext = new GenericXmlApplicationContext("classpath:/spring-*.xml");
//create mock servlet context
MockServletContext mockServletContext = new MockServletContext();
//create web context
GenericWebApplicationContext webContext = new GenericWebApplicationContext(mockServletContext);
//set attribute
mockServletContext.setAttribute(GenericWebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, webContext);
//set parent context
webContext.setParent(xmlContext);
//refresh context
webContext.refresh();
但是有几个上下文类值得关注。考虑到你的先决条件,我会选择其中之一。
GenericXmlApplicationContext 是ClassPathXmlApplicationContext 和FileSystemXmlApplicationContext 的很好替代品。考虑这个例子:
ApplicationContext context = new GenericXmlApplicationContext("classpath:some-context.xml");
等价于
ApplicationContext context = new ClassPathXmlApplicationContext("some-context.xml");
或
ApplicationContext context = new GenericXmlApplicationContext("some-context.xml");
等价于
ApplicationContext context = new FileSystemXmlApplicationContext("some-context.xml");
所以GenericXmlApplicationContext 看起来更灵活。
AnnotationConfigApplicationContext 是上下文持有者,如果您不想将 bean 保存在 XML 文件中。
//context creation
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
//context class
@Configuration
@ComponentScan("com.examples.services")
public class AppConfig {
@Bean
public DataSources dataSource() {
DataSource ds = new BasicDataSource();
//... init ds
return ds;
}
}
更多信息您可以找到here。