简体   繁体   中英

Spring Boot can't find my autowired class (Autowired members must be defined in valid Spring bean)

I'm trying to use Spring's autowire annotation in my test class in order to inject an instance of a class.

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);
    }
}

This is the FormsDB class:

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()));
    }
}

And here is the SpringBootApplication class:

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
}

When I run my test, formsDB is null. Since I've used the PostConstruct annotation on the test function I think that FormsDB could not be autowired due to the class not being found. There is also an IntelliJ warning on the Autowired annotation in test class: Autowired members must be defined in valid Spring bean (@Component|@Service...) . But I have put the Component annotation above the FormsDB class and I've also put the path com.mycom.mycust in the ComponentScan annotation of the SpringBootApplication. So I can't see why it can't find the class.

What is wrong here?

Your test calls is missing some important annotations to make autowiring work:

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

    @Autowired
    private FormsDB formsDB;

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

also you can remove @PostConstruct that does not make sense in a test.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM