Spring Mvc线程中对象的使用

    xiaoxiao2023-05-27  3

    开发中为了运行效率,我们会将一些非主流程游比较耗时间的操作剥离出主线程操作,另起一个线程处理,但在刚接触spring线程的时候,对对象的处理出现了问题,在使用的对象的时候依旧用了比较传统的@Resource注入,但运行之后却报空指针异常,请教别人之后才知道线程中无法使用注解注入对象,web容器启动之前是不会注入线程中的对象的,线程启动时web容器也无法感知。

    那我们在线程中如何使用spring容器中的对象呢?我们可以使用spring上下文直接获取spring容器中的对象,将线程的分发与实现分离。

    首先定义工具类:

    记住该工具类也要被配置为spring的bean,否则无法实例化ApplicationContext导致空指针异常。在你的springbean配置文件加入如下配置:

    <bean id="springBeanUtils" class="com.hujin.common.util.SpringBeanUtils"/>

    此外。要实现ApplicationContext的自动装配,还需要在web.xml文件中加入如下配置:

    <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> ContextLoaderListener的作用就是启动Web容器时,自动装配ApplicationContext的配置信息,context-param指定读取的spring配置,以上配置缺一不可,否则会导致空指针异常。

    此外还有一个注意点,这是我犯得一个错误也在这儿说一下。我开始取bean的时候这样定义,发现报了NoBeanDefinition的错

    private SupplyPoMapper supplyPoMapper = (SupplyPoMapper)SpringBeanUtils.getBean("SupplyPoMapper"); 将getBean中的SupplyPoMapper改为小写supplyPoMapper解决了问题,spring注解扫描类到容器中时以小写字母开头命名。

    转载请注明原文地址: https://ju.6miu.com/read-1260748.html
    最新回复(0)