首页 > 解决方案 > 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 的注解中。所以我不明白为什么它找不到课程。

这里有什么问题?

标签: javaspringspring-boot

解决方案


您的测试调用缺少一些重要的注释来使自动装配工作:

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

    @Autowired
    private FormsDB formsDB;

    @Test
    public void testCreateTopLevelReferencesFrom() throws Exception {
        ReferenceIdentifier referenceIdentifier = new ReferenceIdentifier(formsDB);
    }
}

您也可以删除在测试中没有意义的@PostConstruct。


推荐阅读