37ea74ed9222ea29d6e3f5f26ce23d479460909b.svn-base 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package org.jeecg.common.util;
  2. import javax.servlet.http.HttpServletRequest;
  3. import org.jeecg.common.constant.ServiceNameConstants;
  4. import org.springframework.beans.BeansException;
  5. import org.springframework.context.ApplicationContext;
  6. import org.springframework.context.ApplicationContextAware;
  7. import org.springframework.stereotype.Component;
  8. import org.springframework.web.context.request.RequestContextHolder;
  9. import org.springframework.web.context.request.ServletRequestAttributes;
  10. @Component
  11. public class SpringContextUtils implements ApplicationContextAware {
  12. /**
  13. * 上下文对象实例
  14. */
  15. private static ApplicationContext applicationContext;
  16. @Override
  17. public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  18. SpringContextUtils.applicationContext = applicationContext;
  19. }
  20. /**
  21. * 获取applicationContext
  22. *
  23. * @return
  24. */
  25. public static ApplicationContext getApplicationContext() {
  26. return applicationContext;
  27. }
  28. /**
  29. * 获取HttpServletRequest
  30. */
  31. public static HttpServletRequest getHttpServletRequest() {
  32. return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
  33. }
  34. /**
  35. * 获取项目根路径 basePath
  36. */
  37. public static String getDomain(){
  38. HttpServletRequest request = getHttpServletRequest();
  39. StringBuffer url = request.getRequestURL();
  40. //微服务情况下,获取gateway的basePath
  41. String basePath = request.getHeader(ServiceNameConstants.X_GATEWAY_BASE_PATH);
  42. if(oConvertUtils.isNotEmpty(basePath)){
  43. return basePath;
  44. }else{
  45. return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
  46. }
  47. }
  48. public static String getOrigin(){
  49. HttpServletRequest request = getHttpServletRequest();
  50. return request.getHeader("Origin");
  51. }
  52. /**
  53. * 通过name获取 Bean.
  54. *
  55. * @param name
  56. * @return
  57. */
  58. public static Object getBean(String name) {
  59. return getApplicationContext().getBean(name);
  60. }
  61. /**
  62. * 通过class获取Bean.
  63. *
  64. * @param clazz
  65. * @param <T>
  66. * @return
  67. */
  68. public static <T> T getBean(Class<T> clazz) {
  69. return getApplicationContext().getBean(clazz);
  70. }
  71. /**
  72. * 通过name,以及Clazz返回指定的Bean
  73. *
  74. * @param name
  75. * @param clazz
  76. * @param <T>
  77. * @return
  78. */
  79. public static <T> T getBean(String name, Class<T> clazz) {
  80. return getApplicationContext().getBean(name, clazz);
  81. }
  82. }