servlet调用spring容器中的bean,的两种方式一种注解一种xml配置
最近由于项目中出现了Servlet调用Spring的bean,由于整个项目中所有的bean均是注解方式完成,如@Service,@Repository,@Resource等,但是Spring的容器管理是不识别Servlet和filter的,所以无法使用注解方式引用,在网上查了资料后看到如下的代码:第一种方式:在Servlet的init方法中来完成bean的实例化,初始化后可以在servlet中
·
最近由于项目中出现了Servlet调用Spring的bean,由于整个项目中所有的bean均是注解方式完成,如@Service,@Repository,@Resource等,但是Spring的容器管理是不识别Servlet和filter的,所以无法使用注解方式引用,在网上查了资料后看到如下的代码:
第一种方式:在Servlet的init方法中来完成bean的实例化,初始化后可以在servlet中调用bean中的方法 第二种方式:直接在Servlet的doPost方法中获取,代码如下 不过在我的项目中使用上面任何一种都无法得到任何bean,原因是上面的两种方式只对xml配置的bean有效,无法获取到注解的bean,最后在网上看到一篇关于“Spring对注解(Annotation)处理源码分析——扫描和读取Bean定义”的文章,才终于解决了这个问题,代码如下:
代码1:Service接口 代码2:实现接口并使用注解方式 代码3:在Servlet中获取注解的bean并调用其测试方法 这样就可以在Servlet或者filter中调用Spring注解方式的bean,其实整个过程就是模拟了SpringMVC在初始化的时候扫描组件包后完成对所有bean的注册并存放至管理容器中。如果大家有更好的解决办法,希望不吝赐教!
第一种方式:在Servlet的init方法中来完成bean的实例化,初始化后可以在servlet中调用bean中的方法 第二种方式:直接在Servlet的doPost方法中获取,代码如下 不过在我的项目中使用上面任何一种都无法得到任何bean,原因是上面的两种方式只对xml配置的bean有效,无法获取到注解的bean,最后在网上看到一篇关于“Spring对注解(Annotation)处理源码分析——扫描和读取Bean定义”的文章,才终于解决了这个问题,代码如下:
代码1:Service接口 代码2:实现接口并使用注解方式 代码3:在Servlet中获取注解的bean并调用其测试方法 这样就可以在Servlet或者filter中调用Spring注解方式的bean,其实整个过程就是模拟了SpringMVC在初始化的时候扫描组件包后完成对所有bean的注册并存放至管理容器中。如果大家有更好的解决办法,希望不吝赐教!
更多推荐
已为社区贡献1条内容
所有评论(0)