雨翔河
首页
列表
关于
spring获取bean实例
2016-12-29 14:12
>在web项目中获取springbean,有时候我们需要在非spring组件中获取springbean,我们如果希望在我们的项目中任何位置都能拿到同一个ApplicationContext来获取IOC容器中的资源,就要让Spring将上下文环境填充到我们能获取的地方 最简单的方案就是自己写一个SpringContextUtil来获取。 代码如下: ``` public class SpringContextUtil implements ApplicationContextAware { private static final Logger logger = LoggerFactory.getLogger(SpringContextUtil.class); private static ApplicationContext context = null; /* * @Title: setApplicationContext * @Description: spring获取bean工具类 * @param applicationContext * @throws BeansException * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext) */ @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringContextUtil.context = applicationContext; } @SuppressWarnings("unchecked") public static <T> T getBean(String beanName) { return (T) SpringContextUtil.context.getBean(beanName); } public static String getMessage(String key) { return context.getMessage(key, null, Locale.getDefault()); } } ``` 有一个quartz任务需要执行,它是在spring组件之外的,代码如下: ``` public class VisitorWriteTask extends QuartzJobBean { private static final Logger logger = LoggerFactory.getLogger(VisitorWriteTask.class); @Override protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException { this.work(); } public void work() { try { logger.info("VisitorWriteTask is start"); VisitorService visitorService = SpringContextUtil.getBean("visitorService"); visitorService.writeVisitor(); logger.info("VisitorWriteTask is end"); } catch (Exception e) { logger.error(e.getMessage()); } } } ``` 这样通过直接`SpringContextUtil.getBean("visitorService") `就可以获得visitorService这个实例bean。
类型:工作
标签:spring,java
Copyright © 雨翔河
我与我周旋久
独孤影
开源实验室