1.
<bean id="springContextUtil" class="com.xx.SpringContextUtil"/>
2.
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/****
* SpringContext 上下文
* 通过SpringContext获取Spring管理的业务Bean对象
*
*/
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String name) throws BeansException {
return applicationContext.getBean(name);
}
}
3.调用
private Iservice service;
public MyBatchProcess(){
this.service= (Iservice)SpringContextUtil.getBean("service");
}
本文介绍了一种使用Spring框架管理业务Bean的方法。通过定义SpringContextUtil工具类实现ApplicationContextAware接口,可以在任何地方获取到Spring上下文并从中获取所需的Bean实例。这种方式避免了依赖注入的繁琐步骤,便于进行批处理等任务。
284

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



