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);
}
}