Thread子类中,不能使用Spring注解,变量为null

来源:互联网 发布:对淘宝客服的理解 编辑:程序博客网 时间:2024/05/21 22:41

线程里面,不能使用注解,Spring本身默认Bean为单例模式构建,同时是非线程安全的,因此禁止了在Thread子类中的注入行为,因此在Thread中直接注入的bean是null的。
解决办法有很多个,可自行在网上搜索,本文的解决办法如下:

  1. 创建SpringContextUtils类如下。
package com.vdes.modles.utils;import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;import org.springframework.stereotype.Repository;import org.springframework.util.Assert;@Repositorypublic class SpringContextUtils implements ApplicationContextAware {    private static ApplicationContext applicationContext;    @Override    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {        this.applicationContext = applicationContext;    }    public static ApplicationContext getContext() {        return applicationContext;    }    /**     * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.     */    @SuppressWarnings("unchecked")    public static <T> T getBean(String name) {        checkApplicationContext();        return (T) applicationContext.getBean(name);    }    /**     * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.     */    @SuppressWarnings("unchecked")    public static <T> T getBean(Class<T> clazz) {        checkApplicationContext();        return (T) applicationContext.getBeansOfType(clazz);    }    private static void checkApplicationContext() {        Assert.notNull(applicationContext,                "applicaitonContext未注入,请在applicationContext.xml中定义SpringContextUtil");    }}

由于线程内不能使用注解,可以使用该类来获取bean

  1. 在Spring配置文件中,添加如下代码,配置bean
    <bean lass="com.vdes.modles.utils.SpringContextUtils"/> 

3.在线程类里面,使用如下代码来获取bean

   VdesMessageService vdesMessageService = SpringContextUtils.getBean("vdesMessageServiceImpl");

这里需要注意的是,getBean()的参数应该为配置bean的id,由于本项目使用了注解扫描,并没有为每一个类去配置bean,在使用id的时候,Spring默认id为类名首字母小写。记住,getBean,get的只能是对象,对应的是Class ,而不能是接口,使用Service的时候,要使用它的具体实现类。

0 0
原创粉丝点击