【发布时间】:2018-05-30 06:34:36
【问题描述】:
我有一个带有 Repository(s) 的 Spring Boot 应用程序。
我也使用@Service 并在其中扩展repository。
当我尝试@Autowired 我拥有的服务时:
原因:org.springframework.beans.factory.NoSuchBeanDefinitionException:没有“com.api.core.service.CountryService”类型的合格 bean 可用:预计至少有 1 个有资格作为自动装配候选者的 bean。依赖注解:{@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.**";
}
【问题讨论】:
-
annotate
CountryServiceclass with@Component? -
@flakes 它是一个事务性的
@Service和@Service根据 spring 文档也被@ComponentScan捕获
标签: java spring hibernate spring-mvc