首页 > 解决方案 > 使用 Spring Autowired 注解时的 Nullpoint

问题描述

我正在尝试学习 Spring,但在使用@Autowired注释时遇到了一些麻烦。当我尝试运行下面的示例时,我在classA.hello();网上遇到了一个空点错误,我不知道为什么。任何 hwlp 将不胜感激。

测试类

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;

@ContextConfiguration(classes = {ContextConfigurationClass.class})
public class ClassATest {

    @Autowired
    ClassA classA;

    @Test
    public void test(){
        classA.hello();
    }
    }    

A类

package com;

import org.springframework.stereotype.Service;

@Service
public class ClassA {

    public void hello(){
        System.out.println("HELLO");
    }
}

上下文配置

package com;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan({"com"
})
public class ContextConfigurationClass {

}

标签: javaspringspring-boot

解决方案


NullPointerException 发生是因为测试没有创建 Spring 上下文,因此没有注入 ClassA。

要解决此问题,请添加@RunWith(SpringRunner.class)到 ClassATest。


推荐阅读