gpt4 book ai didi

java - 为什么我不能直接在测试中 @Autowired 我的服务以及为什么我需要 @Autowired 存储库?

转载 作者:行者123 更新时间:2023-12-02 11:51:40 28 4
gpt4 key购买 nike

我有一个带有存储库的 Spring Boot 应用程序。

我还使用@Service并扩展其中的存储库

当我尝试 @Autowired 我拥有的服务时:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.api.core.service.CountryService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

如果我@Autowired存储库,它就可以正常工作。

我的测试必须如下所示:

@SpringBootTest
@ActiveProfiles("core")
@ContextConfiguration(classes = { UserManagementConfig.class, UserManagementServiceConfig.class })
@UserManagementTx
@RunWith(SpringRunner.class)
public class BlogPostContentImplTest {
@Autowired
private CountryService countryService;
@Autowired
private BlogPostContentRepository blogPostContentRepository;
private BlogPostContentServiceImpl blogPostContentService;
private BlogPostContent entity = new BlogPostContent();
@Before
public void setUp() throws Exception {
blogPostContentService = new BlogPostContentServiceImpl(blogPostContentRepository);
List<Country> countryList = countryService.findAll(null);
entity = new BlogPostContent();
entity.setId(1L);
entity.setDescription("test");
entity.setCountry(countryList.get(0));
blogPostContentService.insert(entity);
}

@After
public void tearDown() throws Exception {
blogPostContentService.delete(entity.getId());
}

@Test
public void findAll() throws Exception {
assertThat(blogPostContentService.findAll(null).size()).isGreaterThan(0);
}

}

这就是我配置上下文的方式:

@Configuration
@ComponentScan({
UserManagementConfig.CONTEXT_CLASSPATH
})
public class UserManagementConfig {
public static final String CONTEXT_CLASSPATH = "com.api.userManagement.config.context.**";
}

@Configuration
@ComponentScan({
UserManagementServiceConfig.CLASSPATH,
})
public class UserManagementServiceConfig {

public static final String CLASSPATH = "com.api.userManagement.service.**";

}

最佳答案

根据您发布的代码,您似乎可能需要在测试上下文类之一中对 com.api.core.service.CountryService Bean 进行组件扫描 UserManagementConfigUserManagementServiceConfig

@ComponentScan({
basePackages = {"com.api.core.service"}
})
<小时/>

要测试应用程序上下文是否加载您的 bean,您可以创建一个 TestContext 类,如下所示

@Configuration
@ComponentScan(basePackages = "com.api.core.service")
public class TestContext implements CommandLineRunner {

public static void main(String[] args) {
SpringApplication.run(TestContext.class, args);
}
}

在您的测试中配置TestContext,如下所示

@ContextConfiguration(classes = {TestContext.class})

关于java - 为什么我不能直接在测试中 @Autowired 我的服务以及为什么我需要 @Autowired 存储库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47842680/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com