使用@SpringBootTest,依赖注入失败

时间:2017-05-18 18:11:30

标签: java spring spring-boot

我使用Spring Boot 1.5.3.RELEASE构建一个新的MVC应用程序。

我有一个Customer实体,如下所示:

@Entity
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name = "name", length = 100, nullable = false)
    private String name;

    @Column(name = "enabled", nullable = false)
    private boolean enabled;
}

我有一个CustomerRepository,如下所示:

public interface CustomerRepository extends CrudRepository<Customer, Integer> {

}

我有一个CustomerService,如下所示:

@Service
public class CustomerService {

    @Autowired
    CustomerRepository customerRepository;

    @Autowired
    CustomerMapper customerMapper;

    public CustomerDto save(CustomerDto customerDto) {

        Customer customer = customerMapper.map(customerDto, Customer.class);

        customerRepository.save(customer);

        return customerMapper.map(customer, CustomerDto.class);
    }

    public CustomerDto findById(int id) {

        Customer customer = customerRepository.findOne(id);

        return customerMapper.map(customer, CustomerDto.class);
    }
}

我的申请被定义为:

@SpringBootApplication
public class CoreApplication {

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

我的JPA配置是:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories
public class PersistenceConfig {

}

我写了一个测试如下:

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

    @Autowired
    CustomerService customerService;

    @Test
    public void testCustomerService() {

        CustomerDto customerDtoIn = new CustomerDto();

        customerDtoIn.setName("Test Customer");
        customerDtoIn.setEnabled(true);

        customerService.save(customerDtoIn);

        CustomerDto customerDtoOut = customerService.findById(customerDtoIn.getId());

        assertThat(customerDtoOut).isEqualTo(customerDtoIn);
    }
}

我遵循的结构是:

com.app.core <- CoreApplication lives here
com.app.core.repositories <- Repositories here
com.app.core.services <- Services here

但是,当我尝试运行此测试用例时,我得到以下内容:

org.springframework.beans.factory.NoSuchBeanDefinitionException
No qualifying bean of type 'com.app.core.repositories.CustomerRepository' available

有人能告诉我为什么依赖注入失败了吗?通过阅读spring-boot文档@SpringBootTest@RunWith(SpringRunner.class),我只需要测试我的服务层。

1 个答案:

答案 0 :(得分:0)

您必须将基础包和存储库基础包添加到ApplicationContext.xml。你可以使用下面的代码: -

<context:component-scan annotation-config="true"
    base-package="com.demo.test" />

<jpa:repositories base-package="com.demo.test.repository" />