spring web应用中new出来的Bean实现属性注入的方法

在spring web应用中,几乎所有的Bean的生命周期都是由spring控制的。但有时候我们想在自己new出来的对象中注入spring管理的bean属性,该怎么办呢?

比如下面的应用场景:有一套spring的web管理系统,用到finereport报表插件,而报表插件的数据源是java Bean,改java Bean的实例化是通过finereport插件new出来的,该Bean中用到的hibernate XXDao是由spring管理的,无法注入,解决方案如下:

  a. 在web.xml中配置一个监听

<listener>  
        <listener-class>  
            org.springframework.web.context.request.RequestContextListener  
        </listener-class>  
</listener>  

   b.用下面的方法获取request

HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(); 

  c.通过Spring提供的工具类获取ApplicationContext对象

ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc);
ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc);

说明:
这种方式适合于采用Spring框架的B/S系统,通过ServletContext对象获取ApplicationContext对象,然后在通过它获取需要的类实例。

上面两个工具方式的区别是,前者在获取失败时抛出异常,后者返回null。

其中 servletContext sc 可以具体 换成 servlet.getServletContext()或者 this.getServletContext() 或者 request.getSession().getServletContext(); 另外,由于spring是注入的对象放在ServletContext中的,所以可以直接在ServletContext取出 WebApplicationContext 对象: WebApplicationContext webApplicationContext = (WebApplicationContext) servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

  d.通过ApplicationContext获取注入的Bean对象

ac1.getBean("beanId");
ac2.getBean("beanId");
至此,我们可以愉快的使用spring注入的对象了!由此可见,spring框架设计精巧,学会灵活应用才能掌握spring的真谛啊。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值