我正在按照TDD方法开发Spring Boot应用程序。我通过以下方式创建了主要类(控制器,服务和存储库):
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class CrimeServiceImpl implements CrimeService{
@Autowired
private CrimeRepository repository;
...
控制器:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CrimeController {
@Autowired
private CrimeServiceImpl service = new CrimeServiceImpl();
存储库:
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CrimeRepository extends JpaRepository<Crime, Long>{
}
这是项目结构:
如果我正常运行该应用程序,则没有错误。类的方法为空。然后,我创建了一个像这样的测试类:
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = CrimeServiceImpl.class)
@ComponentScan("com.springmiddleware")
@AutoConfigureMockMvc
@SpringBootTest
public class TestCrimeService {
//Calling method getAllCrimes works
@Test
public void returnAllCrimesExists() throws NoSuchMethodException, SecurityException {
List<Crime> list = new ArrayList<>();
assertTrue(this.service.getAllCrimes() == list);
}
如果我运行此命令,则会显示以下错误,并且测试失败:
NoSuchBeanDefinitionException: No qualifying bean of type 'com.springmiddleware.repository.CrimeRepository' available: expected at least 1 bean which qualifies as autowire candidate.
我已经检查了所有注释,在我看来一切都还不错,我想如果错过了什么,即使在正常运行下,应用程序也会失败。我怎么了?