spring有多个实例化的入口,其中一个为以下:
ApplicationContext act = new ClassPathXmlApplicationContext("application-context.xml");
JdbcTemplate jdbcTemplate = (JdbcTemplate) act.getBean("jdbcTemplate");
如果在非web项目中使用spring框架来管理所有的对象的话,可以通过这样的方式来获得spring上下文,来使用其管理的所有bean。但是每次获得上下文都这么写的话,实际上是实例化了多个spring上下文,这样其中的bean状态并不一致,并且不是单例模式,会造成很多问题。所以需要将spring上下文在系统中只保留一份实例,即采用单例模式获得spring上下文,可以采用如下方式:
编写获取spring ApplicationContext的上下文单例饿汉工具类:
/**
*
* @ClassName: ApplicationContextBean
* @Description: 获取 ApplicationContext
* @author zhangw
*
*/
public class ApplicationContextBean {
static private ApplicationContext ac = null;
static {
ac = new ClassPathXmlApplicationContext("application-context.xml");
}
private ApplicationBean() {
}
/**
*
* @Title: getAc
* @Description: 获取ApplicationContext上下文对象
* @param @return
* @return ApplicationContext
* @author zhangw
*/
public static ApplicationContext getAc() {
return ac;
}
}
在其他地方获取 spring ApplicationContext:
ApplicationContext act = ApplicationContextBean.getAc();
Bean bean = (Bean) act.getBean("bean");
有问题欢迎指出。