注意:这是一个常见问题的规范答案。

我有一个Spring @Service类(MileageFeeCalculator),它有一个@Autowired字段(rateService),但当我尝试使用它时,该字段为空。日志显示正在创建MileageFeeCalculator bean和MileageRateService bean,但是每当我试图在服务bean上调用mileageCharge方法时,都会得到一个NullPointerException。为什么Spring没有自动装配该字段?

控制器类:

@Controller
public class MileageFeeController {    
    @RequestMapping("/mileage/{miles}")
    @ResponseBody
    public float mileageFee(@PathVariable int miles) {
        MileageFeeCalculator calc = new MileageFeeCalculator();
        return calc.mileageCharge(miles);
    }
}

服务类:

@Service
public class MileageFeeCalculator {

    @Autowired
    private MileageRateService rateService; // <--- should be autowired, is null

    public float mileageCharge(final int miles) {
        return (miles * rateService.ratePerMile()); // <--- throws NPE
    }
}

服务bean,应该在MileageFeeCalculator自动连接,但它不是:

@Service
public class MileageRateService {
    public float ratePerMile() {
        return 0.565f;
    }
}

当我尝试GET /mileage/3时,我得到了这个异常:

java.lang.NullPointerException: null
    at com.chrylis.example.spring_autowired_npe.MileageFeeCalculator.mileageCharge(MileageFeeCalculator.java:13)
    at com.chrylis.example.spring_autowired_npe.MileageFeeController.mileageFee(MileageFeeController.java:14)
    ...

当前回答

我认为您错过了指示spring扫描带有注释的类。

您可以在spring应用程序的配置类上使用@ComponentScan("packageToScan")来指示spring进行扫描。

@Service, @Component等注释添加元描述。

Spring只注入这些类的实例,这些类要么创建为bean,要么用注释标记。

在注入之前,spring需要标识带有注释的类,@ComponentScan指示spring查找带有注释的类。当Spring找到@Autowired时,它会搜索相关的bean,并注入所需的实例。

仅仅添加注释,并不能修复或促进依赖注入,Spring需要知道在哪里查找。

其他回答

实际上,您应该使用JVM托管对象或spring托管对象来调用方法。 在控制器类中的上述代码中,您创建了一个新对象来调用服务类,该服务类具有一个自动连接的对象。

MileageFeeCalculator calc = new MileageFeeCalculator();

所以它不会这样工作。

该解决方案使这个MileageFeeCalculator作为控制器本身的自动连接对象。

像下面这样更改你的Controller类。

@Controller
public class MileageFeeController {

    @Autowired
    MileageFeeCalculator calc;  

    @RequestMapping("/mileage/{miles}")
    @ResponseBody
    public float mileageFee(@PathVariable int miles) {
        return calc.mileageCharge(miles);
    }
}

这似乎是一种罕见的情况,但以下是发生在我身上的情况:

我们使用了@Inject而不是@Autowired,后者是Spring支持的javaee标准。每个地方都工作正常,豆子注射正确,而不是一个地方。豆子注射看起来是一样的

@Inject
Calculator myCalculator

最后我们发现错误是我们(实际上是Eclipse自动完成特性)导入了com.opensymphony.xwork2。注入而不是javax.inject.Inject !

总结一下,确保你的注释(@Autowired, @Inject, @Service,…)有正确的包装!

如果这发生在测试类中,请确保您没有忘记注释类。

例如,在Spring Boot中:

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyTests {
    ....

一段时间过去了……

Spring Boot继续发展。如果您使用正确的JUnit版本,则不再需要使用@RunWith。

要让@SpringBootTest单独工作,您需要使用JUnit5中的@Test而不是JUnit4。

//import org.junit.Test; // JUnit4
import org.junit.jupiter.api.Test; // JUnit5

@SpringBootTest
public class MyTests {
    ....

如果配置错误,测试将被编译,但是@Autowired和@Value字段(例如)将为空。由于Spring Boot的操作方式很神奇,因此可以直接调试此故障的方法很少。

您还可以使用服务类上的@Service注释来修复这个问题,并将所需的bean类a作为参数传递给其他bean类b构造函数,并使用@Autowired注释类b的构造函数。示例代码片段如下:

@Service
public class ClassB {

    private ClassA classA;

    @Autowired
    public ClassB(ClassA classA) {
        this.classA = classA;
    }

    public void useClassAObjectHere(){
        classA.callMethodOnObjectA();
    }
}

我认为您错过了指示spring扫描带有注释的类。

您可以在spring应用程序的配置类上使用@ComponentScan("packageToScan")来指示spring进行扫描。

@Service, @Component等注释添加元描述。

Spring只注入这些类的实例,这些类要么创建为bean,要么用注释标记。

在注入之前,spring需要标识带有注释的类,@ComponentScan指示spring查找带有注释的类。当Spring找到@Autowired时,它会搜索相关的bean,并注入所需的实例。

仅仅添加注释,并不能修复或促进依赖注入,Spring需要知道在哪里查找。