applicationContext工具類
阿新 • • 發佈:2019-01-06
applicationContext工具類, 其實現方式有多種. 比如實現ApplicationContextAware.
或者通過@Autowired注入. 或者將其作為工具類成員變數, 通過構造方法注入(spring新特性, 會在初始化bean時, 將其有例項注入其建構函式中的引數中). 如下程式碼是第一種實現.
程式碼如下
package com.markor.hello.applicationcontext; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; /** * @describe: applicationContextUtils工具類 * @author: caichangmeng <
[email protected]> * @since: 2018/10/24 */ @Component public class ApplicationContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } public Object getBean(Class clazz) { return applicationContext.getBean(clazz); } }