Browse Source

编写common

NorthLan 7 years ago
parent
commit
17ed89b6bf

+ 37 - 0
zen-common/src/main/kotlin/com/gxzc/zen/common/util/SpringContextHolder.kt

@@ -0,0 +1,37 @@
+package com.gxzc.zen.common.util
+
+import org.springframework.context.ApplicationContext
+import org.springframework.context.ApplicationContextAware
+import org.springframework.stereotype.Component
+
+/**
+ *
+ * @author NorthLan
+ * @date 2018/2/1
+ * @url https://noahlan.com
+ */
+@Component
+class SpringContextHolder : ApplicationContextAware {
+    companion object {
+        private var applicationContext: ApplicationContext? = null
+            get() {
+                if (field == null) {
+                    throw RuntimeException("Please check if SpringContextHolder has been autowired")
+                }
+                return field
+            }
+
+        @Suppress("UNCHECKED_CAST")
+        fun <T> getBean(beanName: String): T {
+            return applicationContext?.getBean(beanName) as T
+        }
+
+        fun <T : Any> getBean(requiredType: Class<T>): T? {
+            return applicationContext?.getBean(requiredType)
+        }
+    }
+
+    override fun setApplicationContext(applicationContext: ApplicationContext?) {
+        SpringContextHolder.applicationContext = applicationContext
+    }
+}