Java web中获取bean对象

  本案例的使用场景为在ServletContextListener监听器中起一个线程,在线程中需要调用spring中的bean对象。
  首先servlet的生命周期和spring的生命周期不同,所以不能直接在监听器中使用@Autowired和@Resource注入bean。所以需要通过特殊手段拿到bean对象。而spring提供给获取方法有多种
  比较常用的为实现ApplicationContextAware接口,并通过实现类取得bean对象

@Component
public class SpringBeanUtil implements ApplicationContextAware {
    public static ApplicationContext applicationContext = null;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws             
                BeansException {
        // TODO Auto-generated method stub
        SpringBeanUtil.applicationContext = applicationContext;
    }
    
    /**
     * 从静态变量applicationContext中得到Bean, 自动转型为所赋值对象的类型.
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        if(name == null || applicationContext == null)
            return null;
        return (T) applicationContext.getBean(name);
    }
 
    /**
     * 从静态变量applicationContext中得到Bean, 自动转型为所赋值对象的类型.
     */
    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }
 
}

此时需要注意几点:

  1. 需要加上@Component注解,让该类载入spring容器
  2. 在web.xml中加入ContextLoaderListener监听,让容器自动装配spring上下文对象
  3. 确保applicationContext扫描到这个工具类
  4. 确保工具类和使用类正确的加载顺序,加载顺序如下
        <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:config/spring/applicationContext.xml</param-value>
    </context-param>
    
    <!-- ContextLoaderListener监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    <listener>
        <listener-class>com.factory.pro.listener.WarningDataListener</listener-class>
    </listener>

之后就可以在使用类中通过SpringBeanUtil获取相应bean对象进行使用了

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容