原因

  1. 配置缺失,比如为开启注解扫描驱动、注入组件为注册;
  2. 使用 new 关键字创建的对象不受spring容器管理,无法注入;
  3. 注入静态变量, 静态变量/类变量不是对象的属性,而是一个类的属性,spring则是基于对象层面上的依赖注入。

懂的直接上代码先

静态注入的三种方式

在一些工具类中可能会依赖 service 层的对象,一般情况下工具类都是使用静态方法,对应的成员变量也需要声明为静态的,此时如果直接使用 @Autowired 进行依赖注入,在方法调用的时候会报 NullpointerException.

@Autowired
private static AdvancedDatastore dsForRW;

可以试一下,dsForRW在这种状态下不能够被依赖注入,会抛出运行时异常java.lang.NullPointerException,为什么呢?静态变量/类变量不是对象的属性,而是一个类的属性,spring则是基于对象层面上的依赖注入。
但是自己比较喜欢封装工具类,并通过@Component注解成功能组件,但是功能组件中的方法一般都是静态方法,静态方法只能调用静态成员变量,于是就有了下面的问题。封有的时候封装功能组件会需要底层的service注入,怎么办呢?
去网上搜了下解决办法,简单总结一下几种实现方式;

1.xml方式实现
这种方式适合基于XML配置的WEB项目; <bean id="mongoFileOperationUtil" class="com.*.*.MongoFileOperationUtil" init-method="init">
<property name="dsForRW" ref="dsForRW"/>
</bean>
1
2
3
public class MongoFileOperationUtil { private static AdvancedDatastore dsForRW; private static MongoFileOperationUtil mongoFileOperationUtil; public void init() {
mongoFileOperationUtil = this;
mongoFileOperationUtil.dsForRW = this.dsForRW;
} }
2.@PostConstruct方式实现
import org.mongodb.morphia.AdvancedDatastore;
import org.springframework.beans.factory.annotation.Autowired; @Component
public class MongoFileOperationUtil {
@Autowired
private static AdvancedDatastore dsForRW; private static MongoFileOperationUtil mongoFileOperationUtil; @PostConstruct
public void init() {
mongoFileOperationUtil = this;
mongoFileOperationUtil.dsForRW = this.dsForRW;
} }

@PostConstruct 注解的方法在加载类的构造函数之后执行,也就是在加载了构造函数之后,执行init方法;(@PreDestroy 注解定义容器销毁之前的所做的操作)
这种方式和在xml中配置 init-method和 destory-method方法差不多,定义spring 容器在初始化bean 和容器销毁之前的所做的操作;

 

3.set方法上添加@Autowired注解,类定义上添加@Component注解

import org.mongodb.morphia.AdvancedDatastore; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class MongoFileOperationUtil { private static AdvancedDatastore dsForRW; @Autowired public void setDatastore(AdvancedDatastore dsForRW) { MongoFileOperationUtil.dsForRW = dsForRW; } } 首先Spring要能扫描到AdvancedDatastore的bean,然后通过setter方法注入; 然后注意:成员变量上不需要再添加@Autowired注解;

Spring @Autowired 注入为 null的更多相关文章

  1. spring@Autowired注入为null的问题,2017年9月14日21点41分记录

    这个小问题纠结了三个小时..发出来留个纪念 这是启动项目的时候 这是请求控制器的时候   图1注入的时候是null,图2请求控制器的时候是有的,这是因为图1debug的地方是构造器..autowire ...

  2. struts2的action中@Autowired注入为null的解决方案

    今天遇到类似问题,记录下来以便以后查阅: @Aspect作用于action,致使action中的@Autowired注入为null的解决方案,以下三种任选一种: 1.去掉@Autowired,改用se ...

  3. 关于工具类中@Autowired注入为NULL的问题记录

      记录:在实体类中加入@Component注解和@Autowired注解时Service不能注入成功. @Component //把普通pojo实例化到spring容器中 0 public clas ...

  4. Quartz定时器+Spring + @Autowired注入 空指针异常

    在Quartz的定时方法里引用@Autowired注入Bean,会报空指针错误 解决办法: 第一种方法:(推荐,简单,亲测可行) 使用@Resource(name="指定要注入的Bean&q ...

  5. Java 各级注解及@Autowired注入为null解决办法

    1.@controller 控制器 用于标注控制层,相当于struts中的action层. 2.@service 服务层 用于标注服务层,主要用来进行业务的逻辑处理. 3.@repository DA ...

  6. 于工具类中@Autowired注入为NULL的问题记录

      记录:在实体类中加入@Component注解和@Autowired注解时Service不能注入成功. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 ...

  7. Spring Autowired 注入失败总是Null

    报错:NullPointerException 分析:错误原因是注入失败? <context:annotation-config/> <context:component-scan ...

  8. spring @Autowired注入对象,在构造方法中为null问题

    出现问题的代码如下: @Service public class BaseHttpServiceImpl implements BaseHttpClient { private final stati ...

  9. @Autowired注入为null问题分析

    题说明 最近看到Spring事务,在学习过程中遇到一个很苦恼问题 搭建好Spring的启动环境后出现了一点小问题 在启动时候却出现[java.lang.NullPointerException] 不过 ...

随机推荐

  1. Fix multiple GPUs fails in training Mask_RCNN

    Test with: Keras: 2.2.4Python: 3.6.9Tensorflow: 1.12.0 ================== Problem: Using code from h ...

  2. 本地局域网yum源搭建-centos/redhat

    环境-centos6.7  [本机yum搭建提前备好,不做介绍] [root@nagios ~]# cat /etc/redhat-release CentOS release 6.7 (Final) ...

  3. 获取url后的参数、获取a标签的参数

    function getQueryString(name) { var reg = new RegExp("(^|&)" + name + "=([^&] ...

  4. ansible-playbook-常用

    创建软链:file: - name: create link hosts: "{{hosts_ip}}" tasks: - name: create link file: src= ...

  5. 【转】Linux 系统如何处理名称解析

    原文写的很好:https://blog.arstercz.com/linux-%E7%B3%BB%E7%BB%9F%E5%A6%82%E4%BD%95%E5%A4%84%E7%90%86%E5%90% ...

  6. Shell命令行提示定制

    /******************************************************************************* * Shell命令行提示定制 * 说明 ...

  7. Learning to Track Any Object

    Learning to Track Any Object 2019-10-28 12:14:49 Paper: https://arxiv.org/abs/1910.11844 1.

  8. Mysql 查询今天,这周,这个月,今年的数据

    今天 select * from 表名 where to_days(时间字段名) = to_days(now()); 昨天 SELECT * FROM 表名 WHERE TO_DAYS( NOW( ) ...

  9. numpy的文件存储.npy .npz 文件详解

    Numpy能够读写磁盘上的文本数据或二进制数据. 将数组以二进制格式保存到磁盘 np.load和np.save是读写磁盘数组数据的两个主要函数,默认情况下,数组是以未压缩的原始二进制格式保存在扩展名为 ...

  10. Mysql模糊查询like提速优化

    LOCATE('substr',str,pos)方法 SELECT LOCATE('xbar',`foobar`); ###返回0 SELECT LOCATE('bar',`foobarbar`); ...