java - Spring Boot 找不到我的自动装配类(Autowired 成员必须在有效的 Spring bean 中定义)
问题描述
我试图在我的测试类中使用 Spring 的 autowire 注释来注入一个类的实例。
package com.mycom.mycust.processing.tasks.references;
public class ReferenceIdentifierTest {
@Autowired
private FormsDB formsDB;
@PostConstruct
@Test
public void testCreateTopLevelReferencesFrom() throws Exception {
ReferenceIdentifier referenceIdentifier = new ReferenceIdentifier(formsDB);
}
}
这是 FormsDB 类:
package com.mycom.mycust.mysql;
import org.springframework.stereotype.Component;
import java.sql.SQLException;
@Component
public class FormsDB extends KeyedDBTable<Form> {
public FormsDB(ConnectionFactory factory) throws SQLException {
super(factory.from("former", new FormsObjectMapper()));
}
}
这是 SpringBootApplication 类:
package com.mycom.mycust.processing;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan("com.mycom.mycust")
public class Processing implements CommandLineRunner {
// Code
}
当我运行测试时,formsDB
为空。由于我PostConstruct
在测试函数上使用了注释,我认为由于找不到类,FormsDB 无法自动装配。Autowired
测试类中的注释也有一个 IntelliJ 警告: Autowired members must be defined in valid Spring bean (@Component|@Service...)
. 但是我已经将Component
注解放在了FormsDB
类的上方,并且我还将路径com.mycom.mycust
放在ComponentScan
了 SpringBootApplication 的注解中。所以我不明白为什么它找不到课程。
这里有什么问题?
解决方案
您的测试调用缺少一些重要的注释来使自动装配工作:
@SpringBootTest
@RunWith(SpringRunner.class)
public class ReferenceIdentifierTest {
@Autowired
private FormsDB formsDB;
@Test
public void testCreateTopLevelReferencesFrom() throws Exception {
ReferenceIdentifier referenceIdentifier = new ReferenceIdentifier(formsDB);
}
}
您也可以删除在测试中没有意义的@PostConstruct。
推荐阅读
- mysql - 我的架构没有出现在 MySQL WorkBench 架构面板上
- flutter - Flutter Riverpod:发布失败
- jinja2 - 在悬停时显示标题永久链接(鹈鹕)
- nginx - 将 NGINX 设置为客户端内容缓存服务器
- bash - bash脚本:意外标记“完成”附近的语法错误
- linux - Shell 脚本 - 在不同的 bash 会话中并行运行 shell 命令
- webpack - 如何通过 webpack 让中间人使用自定义字体和 font-awesome?
- php - 如何在超过 1 周时隐藏数据,我使用 codeigniter
- javascript - 如何从 TypeORM 属性装饰器中获取值
- reactjs - 如何让 BootstrapTable 用更新的数据重绘?