Thread子类中,不能使用Spring注解,变量为null
来源:互联网 发布:对淘宝客服的理解 编辑:程序博客网 时间:2024/05/21 22:41
线程里面,不能使用注解,Spring本身默认Bean为单例模式构建,同时是非线程安全的,因此禁止了在Thread子类中的注入行为,因此在Thread中直接注入的bean是null的。
解决办法有很多个,可自行在网上搜索,本文的解决办法如下:
- 创建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
- 在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
- Thread子类中,不能使用Spring注解,变量为null
- Spring @Autowired注解在非Controller中注入为null
- Spring 父类注入的属性 在子类中调用为null
- Spring使用注解通过子类注入父类的私有变量
- Spring使用@PostConstruct注解完成子类注入父类私有变量
- spring 在Thread中注入@Resource失败,总为null~解决
- spring 在Thread中注入@Resource@Autowired失败,总为null~解决
- spring 在Thread中注入@Resource失败,总为null的解决方案
- Spring中静态方法中使用@Resource注解的变量
- Spring data elasticsearch注解@Filed和@ManytoMany同时使用,搜索结果取到属性为null
- 解决Quartz的Job类中使用注解Service为null的办法
- 解决@Value注解不能为静态变量赋值
- str不能为null
- 以@Resource为例,透析注解的本质,spring中是如何使用注解的
- Spring MVC中静态变量注解初始化
- 解决非controller使用@Autowired注解注入为null问题
- 使用dynamic_cast将子类转换为父类指针时,结果可能为NULL
- spring mybatis不能使用变量连接数据库
- 学习一
- 离线配置gradle时,打开Android Studio会报错 “Error:Gradle distribution 'https://services.gradle.org/distribution
- ES6 函数扩展
- 蓝牙核心技术与应用学习笔记
- 维基百科搬运 树 (数据结构)
- Thread子类中,不能使用Spring注解,变量为null
- 前端开发中如何解析json数据(二)
- iOS 自定制弹框
- 服务器延迟原因汇总
- @SerializedName注解
- cannot resolve symbol DefaultHttpClient等之类的提示
- c#中全局变量与局部变量的设置
- 欢迎使用CSDN-markdown编辑器
- Leetcode 8. String to Integer (atoi)