在Spring框架中,通常使用ApplicationContext來管理Bean。如果手動創建壹個SpringContextHolder工具類,可以考慮以下實現:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringContextHolder{
private static ApplicationContext context;
public static void setContext(ApplicationContext context){
SpringContextHolder.context= context;
}
public static ApplicationContext getContext(){
return context;
}
public static void clearContext(){
context= null;
}
public static void initContext(String...configLocations){
context= new ClassPathXmlApplicationContext(configLocations);
}
}
以上代碼中,SpringContextHolder類中定義了壹個靜態的ApplicationContext對象context,可以通過setContext()方法進行設置,通過getContext()方法獲取,通過clearContext()方法清空,通過initContext()方法初始化ApplicationContext。
spring的特點
1、方便解耦,簡化開發
通過Spring提供的IoC容器,我們可以將對象之間的依賴關系交由Spring進行控制,避免硬編碼所造成的過度程序耦合。有了Spring,用戶不必再為單實例模式類、屬性文件解析等這些很底層的需求編寫代碼,可以更專註於上層的應用。
2、AOP編程的支持
通過Spring提供的AOP功能,方便進行面向切面的編程,許多不容易用傳統OOP實現的功能可以通過AOP輕松應付。
3、聲明式事務的支持
在Spring中,我們可以從單調煩悶的事務管理代碼中解脫出來,通過聲明式方式靈活地進行事務的管理,提高開發效率和質量。
4、方便程序的測試
可以用非容器依賴的編程方式進行幾乎所有的測試工作,在Spring裏,測試不再是昂貴的操作,而是隨手可做的事情。例如:Spring對Junit4支持,可以通過註解方便的測試Spring程序。