[英]Dependency injection fails with @SpringBootTest
我正在使用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 docs @SpringBootTest
和@RunWith(SpringRunner.class)
,我只需測試一下我的服務層即可。
您必須將基本包和存儲庫基本包添加到ApplicationContext.xml
。 可以使用以下代碼:
<context:component-scan annotation-config="true"
base-package="com.demo.test" />
<jpa:repositories base-package="com.demo.test.repository" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.