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

时间:2017-12-16 05:05:46

标签: java spring hibernate spring-mvc

我有一个Repository(s)的春季启动应用程序。

我也使用@Service并在其中扩展repository

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

  

引起:org.springframework.beans.factory.NoSuchBeanDefinitionException:没有'com.api.core.service.CountryService'类型的限定bean可用:预计至少有1个bean可以作为autowire候选者。依赖注释:{@ 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.**";

}

1 个答案:

答案 0 :(得分:1)

根据您发布的代码,您可能需要在一个测试上下文类$(document).ready(function(){ //Get the selected text var selectedCityText = $('#selectCity :selected').text(); alert(selectedCityText); //Or //Get the selected value var selectedCityValue = $('#selectCity :selected').val(); alert(selectedCityValue); }); com.api.core.service.CountryService

中对UserManagementConfig Bean进行组件扫描
UserManagementServiceConfig

要测试app上下文是否加载了您的bean,您可以创建一个@ComponentScan({ basePackages = {"com.api.core.service"} }) 类,如下所示

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