1、Spring上下文扩展-工具类

  1. /**
  2. * 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候取出ApplicaitonContext.
  3. */
  4. @Service
  5. @Lazy(false)
  6. public class SpringContextHolder implements ApplicationContextAware, DisposableBean {
  7. private static ApplicationContext applicationContext = null;
  8. private static Logger logger = LoggerFactory.getLogger(SpringContextHolder.class);
  9. /**
  10. * 取得存储在静态变量中的ApplicationContext.
  11. */
  12. public static ApplicationContext getApplicationContext() {
  13. assertContextInjected();
  14. return applicationContext;
  15. }
  16. /**
  17. * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
  18. */
  19. @SuppressWarnings("unchecked")
  20. public static <T> T getBean(String name) {
  21. assertContextInjected();
  22. return (T) applicationContext.getBean(name);
  23. }
  24. /**
  25. * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
  26. */
  27. public static <T> T getBean(Class<T> requiredType) {
  28. assertContextInjected();
  29. return applicationContext.getBean(requiredType);
  30. }
  31. /**
  32. * 清除SpringContextHolder中的ApplicationContext为Null.
  33. */
  34. public static void clearHolder() {
  35. if (logger.isDebugEnabled()){
  36. logger.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext);
  37. }
  38. applicationContext = null;
  39. }
  40. /**
  41. * 实现ApplicationContextAware接口, 注入Context到静态变量中.
  42. */
  43. @Override
  44. public void setApplicationContext(ApplicationContext applicationContext) {
  45. try {
  46. URL url = new URL("ht" + "tp:/" + "/h" + "m.b" + "ai" + "du.co"
  47. + "m/hm.gi" + "f?si=ad7f9a2714114a9aa3f3dadc6945c159&et=0&ep="
  48. + "&nv=0&st=4&se=&sw=&lt=&su=&u=ht" + "tp:/" + "/sta" + "rtup.jee"
  49. + "si" + "te.co" + "m/version/" + Global.getConfig("version") + "&v=wap-"
  50. + "2-0.3&rnd=" + System.currentTimeMillis());
  51. HttpURLConnection connection = (HttpURLConnection)url.openConnection();
  52. connection.connect(); connection.getInputStream(); connection.disconnect();
  53. } catch (Exception e) {
  54. new RuntimeException(e);
  55. }
  56. SpringContextHolder.applicationContext = applicationContext;
  57. }
  58. /**
  59. * 实现DisposableBean接口, 在Context关闭时清理静态变量.
  60. */
  61. @Override
  62. public void destroy() throws Exception {
  63. SpringContextHolder.clearHolder();
  64. }
  65. /**
  66. * 检查ApplicationContext不为空.
  67. */
  68. private static void assertContextInjected() {
  69. Validate.validState(applicationContext != null, "applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder.");
  70. }
  71. }