在Servlet中获取Spring注解的bean

本文详细介绍了如何在Spring框架下通过注解方式引用bean于Servlet,包括初始化方法、直接获取bean的方法及扫描组件包完成bean注册的过程。通过实例代码演示了解决方案,帮助开发者克服Spring与Servlet集成时的常见问题。

最近由于项目中出现了Servlet调用Spring的bean,由于整个项目中所有的bean均是注解方式完成,如@Service,@Repository,@Resource等,但是Spring的容器管理是不识别Servlet和filter的,所以无法使用注解方式引用,在网上查了资料后看到如下的代码:
第一种方式:在Servlet的init方法中来完成bean的实例化,初始化后可以在servlet中调用bean中的方法

 

WebApplicationContext cont = WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext()); 
ts=(TestService)cont.getBean("testService")//ts为已经声明的类变量,括号内的名字默认为bean的类名,第一个字母小写,也可以设置唯一名称,如@Service(value="testService")

 

第二种方式:直接在Servlet的doPost方法中获取,代码如下

 

WebApplicationContext cont = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());

 

不过在我的项目中使用上面任何一种都无法得到任何bean,原因是上面的两种方式只对xml配置的bean有效,无法获取到注解的bean,最后在网上看到一篇关于“Spring对注解(Annotation)处理源码分析——扫描和读取Bean定义”的文章,才终于解决了这个问题,代码如下:
代码1:Service接口

 

package com.test.web.service;

public interface ITestService {
public void test();//测试方法
}

 

代码2:实现接口并使用注解方式

 

package com.test.web.service.impl;

import org.springframework.stereotype.Service;

import com.taokejh.web.test.ITestService;
//此处的注解部分可以给出唯一名称,如@Service(value="testServiceImpl"),等同于xml配置中bean的id
@Service
public class TestServiceImpl implements ITestService {

@Override
public void test() {
System.out.println("测试打印");
}

}

 

代码3:在Servlet中获取注解的bean并调用其测试方法

 

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); 
ctx.scan("com.test.web.service.*"); 
ctx.refresh(); 
TestServiceImpl service = ctx.getBean(TestServiceImpl.class);//此处也可以使用ctx.getBean("testServiceImpl") 
service.test();

 

这样就可以在Servlet或者filter中调用Spring注解方式的bean,其实整个过程就是模拟了SpringMVC在初始化的时候扫描组件包后完成对所有bean的注册并存放至管理容器中。如果大家有更好的解决办法,希望不吝赐教!

 

 

 

 

 

转载于:https://www.cnblogs.com/google4y/p/3396139.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值