问题:在filter和interceptor中经常需要调用Spring的bean,filter也是配置在web.xml中的,请问一下这样调用的话,filter中调用Spring的某个bean,这个bean一定存在吗?现在总是担心filter调用bean的时候,bean还没被实例化?

答案:因为spring bean、filter、interceptor加载顺序与它们在 web.xml 文件中的先后顺序无关。即不会因为 filter 写在 listener 的前面而会先加载 filter。最终得出的结论是: ServletContext -> listener -> filter -> servlet

由于spring bean的初始化是在listener中声明的,因此filter时,spring bean已经实例。

注入bean方法:

一、自定义一个工具类,在工具类中通过ApplicationContext获取bean

  自定义一个工具类,实现自ApplicationContextAware接口,接口的方法是setApplicationContext,我们实现它,并让其为我们服务,因为Spring在load自己的时候会将上下文环境填充进来。我们所要做的就是将得到的ApplicationContext保存下来用。

@Component
public class SpringUtil implements ApplicationContextAware { private static Logger log = LoggerFactory.getLogger(SpringUtil.class); /**
* 当前IOC
*/
private static ApplicationContext applicationContext; /*
* @param arg0
*
* @throws BeansException
*
* @see
* org.springframework.context.ApplicationContextAware#setApplicationContext
* (org.springframework.context.ApplicationContext)
*/
@Override
public void setApplicationContext(ApplicationContext arg0) throws BeansException {
log.info("====================arg0:"+arg0);
applicationContext = arg0;
} public static <T>T getBean(String id,Class<T> type){
return applicationContext.getBean(id,type);
}
}

需要注意的是该工具类需要纳入spring的bean管理(注解:增加扫描配置component-scan或bean.xml中配置)哟,否则applicationContext 将会是空的。

二、自定义一个工具类,在工具类中通过BeanFactory 获取bean

  自定义一个工具类,实现自BeanFactoryAware 接口,接口的方法是setBeanFactory,我们实现它,并让其为我们服务,因为Spring在load自己的时候会将上下文环境填充进来。我们所要做的就是将得到的BeanFactory 保存下来用。


@Component
public class BeanHelper implements BeanFactoryAware {

    private static BeanFactory beanFactory;

    @Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
} public static <T>T getBean(String id,Class<T> type){
return beanFactory.getBean(id,type);
}
}

同样,需要注意的是该工具类需要纳入spring的bean管理(注解:增加扫描配置component-scan或bean.xml中配置)哟,否则applicationContext 将会是空的。

二、使用了注解和静态化的方式来产生SpringFactory对象

  上文的方法有个麻烦的地方:需要配置。而Spring2.5及之后的版本实际上加入了注解的方式进行依赖项的注入,使用如下代码也许更好:

public class SpringWiredBean extends SpringBeanAutowiringSupport {

    /**
* 自动装配注解会让Spring通过类型匹配为beanFactory注入示例
*/
@Autowired
private BeanFactory beanFactory; private SpringWiredBean() {
} private static SpringWiredBean instance; static {
// 静态块,初始化实例
instance = new SpringWiredBean();
} /**
* 实例方法 使用的时候先通过getInstance方法获取实例
*
* @param beanId
* @return
*/
public <T>T getBean(String id,Class<T> type){
return beanFactory.getBean(id,type);
} public static SpringWiredBean getInstance() {
return instance;
}
}

但是要增加一个扫描,让spring能知道注解:

<context:component-scan base-package="org.ahe"></context:component-scan>

servlet中注入bean的方法

步骤:

1 配置spring文件

<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>

2 在web.xml中加载spring的配置文件

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:/spring/applicationContext_*.xml
</param-value>
</context-param>

3 在servlet中获取名字为jdbcTemplat的bean.

public class UserAuthorizationFilter extends HttpServlet {

private WebApplicationContext wac;

    public void init(){
//方法一:
wac =WebApplicationContextUtils.getRequiredWebApplicationContext( this.getServletContext()); //方法二:
wac = WebApplicationContextUtils.getWebApplicationContext(
this.getServletContext()); //方法一和方法二得到的结果是一样的。 //wac的类型:
org.springframework.web.context.support.XmlWebApplicationContext } public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { JdbcTemplate jdbcTemplate = (JdbcTemplate)wac.getBean("jdbcTemplate"); String sql="select count(*) from customer where name='liwj' and password='1111111'"; int num=jdbcTemplate.queryForInt(sql);
if(num==1){
System.out.println("has");
}else{
System.out.println("hasnot"); } }

非spring组件servlet、filter、interceptor中注入spring bean的更多相关文章

  1. 如何在servlet的监听器中使用spring容器的bean

    另外补充下:在web Server容器中,无论是Servlet,Filter,还是Listener都不是Spring容器管理的,因此我们都无法在这些类中直接使用Spring注解的方式来注入我们需要的对 ...

  2. JavaWeb三大组件(Servlet,Filter,Listener 自己整理,初学者可以借鉴一下)

    JavaWeb三大组件(Servlet,Filter,Listener 自己整理,初学者可以借鉴一下) Reference

  3. Spring管理Filter和Servlet(在servlet中注入spring容器中的bean)

    在使用spring容器的web应用中,业务对象间的依赖关系都可以用context.xml文件来配置,并且由spring容器来负责依赖对象 的创建.如果要在servlet中使用spring容器管理业务对 ...

  4. 如何在静态方法或非Spring Bean中注入Spring Bean

           在项目中有时需要根据需要在自己new一个对象,或者在某些util方法或属性中获取Spring Bean对象,从而完成某些工作,但是由于自己new的对象和util方法并不是受Spring所 ...

  5. Java(多)线程中注入Spring的Bean

    问题说明 今天在web应用中用到了Java多线程的技术来并发处理一些业务,但在执行时一直会报NullPointerException的错误,问题定位了一下发现是线程中的Spring bean没有被注入 ...

  6. java多线程中注入Spring对象问题

    web应用中java多线程并发处理业务时,容易抛出NullPointerException. 原因: 线程中的Spring Bean没有被注入.web容器在启动时,没有提前将线程中的bean注入,在线 ...

  7. 【转】Java(多)线程中注入Spring的Bean

    问题说明 今天在web应用中用到了Java多线程的技术来并发处理一些业务,但在执行时一直会报NullPointerException的错误,问题定位了一下发现是线程中的Spring bean没有被注入 ...

  8. 【Spring】关于Boot应用中集成Spring Security你必须了解的那些事

    Spring Security Spring Security是Spring社区的一个顶级项目,也是Spring Boot官方推荐使用的Security框架.除了常规的Authentication和A ...

  9. 在非spring组件中注入spring bean

    1.在spring中配置如下<context:spring-configured/>     <context:load-time-weaver aspectj-weaving=&q ...

随机推荐

  1. 【转】IOS图像拉伸解决方案

    原文网址:http://www.cnblogs.com/ios8/p/ios-pic-lashen.html UIButton实现背景拉伸,即图片两端不拉伸中间拉伸的办法有如下两种: 第一种方法很简单 ...

  2. 【转】免费开源的FTP软件,FileZilla

    原文网址:http://baike.baidu.com/view/670329.htm?fr=aladdin FileZilla FileZilla是一个免费开源的FTP软件,分为客户端版本和服务器版 ...

  3. MiniCRT 64位 linux 系统移植记录:64位gcc的几点注意

    32位未修改源码与修改版的代码下载: git clone git@github.com:youzhonghui/MiniCRT.git MiniCRT 64位 linux 系统移植记录 MiniCRT ...

  4. CSS3弹性盒模型之box-orient & box-direction

    Css3引入了新的盒模型——弹性盒模型,其实上一篇文章已经讲到了一个box-flex,今天来讲讲另外的两个弹性盒模型属性box-orient 和 box-direction. 1.box-origen ...

  5. unity, monoDevelop ide 代码提示不起作用的解决方法

    monoDevelop ide 代码提示不起作用,可能是因为ide里索引了一些不存在的文件,检查一下solution窗口里是否有文件变红,如下图中springControlEx.cs.将变红的文件re ...

  6. centos7通过yum安装mysql,并授权远程连接

    安装: CentOS 7的yum源中没有正常安装MySQL的mysql-sever文件,需要去官网上下载(通过安装mysql的yum容器,再通过yum安装mysql) 注:安装前,需要卸载所有的mar ...

  7. Linux-Hostname-details

    转自:http://www.cnblogs.com/kerrycode/p/3595724.html 当我觉得对Linux系统下修改hostname已经非常熟悉的时候,今天碰到了几个个问题,这几个问题 ...

  8. [mysql] linux 下mysql 5.7.12 安装

    1.下载mysql wget http://dev.mysql.com/get/Downloads/MySQL-5.7/mysql-5.7.12-1.el6.x86_64.rpm-bundle.tar ...

  9. 【jmeter】搭建持续集成接口测试平台(Jenkins+Ant+Jmeter)

    一.环境准备: 1.JDK:http://www.oracle.com/technetwork/java/javase/downloads/index.html 2.Jmeter:http://jme ...

  10. LitDB文章

    阅读目录 1.LiteDB初步介绍 2.LiteDB使用基本案例 3.LiteDB的技术细节 4.资源其他 今天给大家介绍一个不错的小巧轻量级的NoSQL文件数据库LiteDB.本博客在2013年也介 ...