SpringMVC中普通类调用Service接口

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

 

 赠人玫瑰手留余香,若对您有帮助,来点个赞呗!

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

踮脚敲代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值