SpringMVC中Controller直接用注解@Resource即可调用Service业务逻辑层,但普通类或者工具类要调用Service接口时,该如何操作呢?
接下来提供两种解决方案
一. 重载Spring配置文件实例化上下文Bean
ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext-common.xml");
StudentService studentService = (StudentService)appContext.getBean("studentService");
通过ClassPathXmlApplicationContext作为入口,加载CLASSPATH下的Spring配置文件,完成对所有Bean实例的加载,并获取Bean的实例。
二. 实现ApplicationContextAware接口(推荐)
通过ApplicationContextAware接口,实现从已有的Spring上下文取得已实例化的Bean。
(1)创建工具类SpringContextUtil实现ApplicationContextAware接口
@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext appCtx;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
appCtx = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return appCtx;
}
// 添加getBean()方法,凭id获取容器管理的Bean
public static Object getBean(String beanName) {
return appCtx.getBean(beanName);
}
}
(2)将工具类SpringContextUtil注入到Spring容器中
<bean id="springContextUtil" class="com.cn.unit.spring.SpringContextUtil"/>
(3)在项目web.xml中配置加载Spring容器的Listener
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
(4)接下来就可以愉快地获取Spring容器中的Bean了
UserServiceImpl userService = (UserServiceImpl) SpringContextUtil.getBean("userService");
userService.insertUser(user);
点个赞
呗!