java - 使用 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 {
}
解决方案
NullPointerException 发生是因为测试没有创建 Spring 上下文,因此没有注入 ClassA。
要解决此问题,请添加@RunWith(SpringRunner.class)
到 ClassATest。
推荐阅读
- ruby-on-rails-6 - Webpacker 在循环中重新编译
- discord.js - 将用户名存储在 quick.db 数据库中
- excel - 跨多行多列的目标搜索宏扫描
- r - 如何替换r中数据框中多行中的值?
- function - 为什么存储函数总是引用更新后的全局 i 变量的值?
- socket.io - 为聊天实现 socket.io 哪个是更好的方法房间还是正常方法?
- next.js - 如何在“createGlobalStyle”中导入顺风
- c++ - 获取 C++ 类成员变量的全名
- python - 错误:requests.exceptions.SSLError: [Errno 2] 当我尝试 py 到 exe 时没有这样的文件或目录
- c# - 带有 IStringLocalizer 的 RazorPages 不起作用