创建一个工具类SpringContextUtil,通过实现Spring中的ApplicationContextAware接口
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ServletContextAware;
import javax.servlet.ServletContext;
@Component
public class SpringContextUtil implements ApplicationContextAware,
ServletContextAware {
// Spring上下文对象.静态变量,可在任何代码任何地方任何时候中取出ApplicaitonContext.
private static ApplicationContext applicationContext;
// 注入 系统上下文对象
private static ServletContext servletContext;
public static Object getBean(String name) throws BeansException {
return applicationContext.getBean(name);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
}
@Override
public void setServletContext(ServletContext servletContext) {
SpringContextUtil.servletContext = servletContext;
}
}
在其他类中调用:
//如果要调用自己的service,可以使用SpringContextUtil来获取,然后执行
HandlerFunction function = (HandlerFunction) SpringContextUtil.getBean("handlerFunction");
本文介绍了一个用于方便获取Spring Bean的工具类SpringContextUtil的实现。该工具类通过实现ApplicationContextAware和ServletContextAware接口,使得开发者可以在项目的任何位置轻松地获取到所需的Spring Bean实例。

9798

被折叠的 条评论
为什么被折叠?



