我使用Spring Initializr生成了一个Spring Boot Web应用程序,使用嵌入式Tomcat + Thymeleaf模板引擎,并打包为可执行的JAR文件。
使用的技术:
Spring Boot 1.4.2.RELEASE,Spring 4.3.4.RELEASE,Thymeleaf 2.1.5.RELEASE,Tomcat Embed 8.5.6,Maven 3,Java 8
我有这个测试:
@ContextConfiguration(classes={PersistenceConfig.class})
@RunWith(SpringRunner.class)
public class BooksManagerTests {
/**
* The object being tested.
*/
@Autowired
BooksManager booksManager;
@Test
public void testfindDeviceByKey() {
booksManager.findDeviceByKey("C380F");
}
}
@Configuration
public class PersistenceConfig {
@Bean
public JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(dataSource());
}
@Bean
public BooksManager booksManager() {
return new BooksManagerImpl();
}
/**
* Creates an in-memory "rewards" database populated
* with test data for fast testing
*/
@Bean
public DataSource dataSource(){
return
(new EmbeddedDatabaseBuilder())
.addScript("classpath:db/H2.schema.sql")
.addScript("classpath:db/H2.data.sql")
.build();
}
}
@Service("booksManager")
public class BooksManagerImpl implements BooksManager {
private DeviceEventRepository deviceEventRepository;
@Autowired
public void setDeviceEventRepository(DeviceEventRepository deviceEventRepository) {
this.deviceEventRepository = deviceEventRepository;
}
@Override
public List<DeviceEvent> getAllDeviceEvents() {
return deviceEventRepository.getAllDeviceEvents();
}
}
@Repository("deviceEventRepository")
public class JdbcDeviceEventRepository implements DeviceEventRepository {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public List<DeviceEvent> getAllDeviceEvents() {
String sql = "select * from t_device_event";
return mapDeviceEvents(jdbcTemplate.queryForList(sql));
}
private List<DeviceEvent> mapDeviceEvents(List<Map<String,Object>> deviceEventsMap) {
return null;
}
}
但运行测试时出现此错误:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'booksManager': Unsatisfied dependency expressed through method 'setDeviceEventRepository' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.tdk.repository.DeviceEventRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
答案 0 :(得分:1)
解决了将此问题添加到PersistenceConfig类
@Bean
public DeviceEventRepository deviceEventRepository() {
return new JdbcDeviceEventRepository();
}
答案 1 :(得分:0)
您的应用程序仅在初始化期间指定单个配置:
@ContextConfiguration(类= {PersistenceConfig.class})
您需要通过指定这样的main来启动应用程序以启用Spring启动自动配置:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
有关JPA存储库自动配置的详细信息,请参阅JpaRepositoriesAutoConfiguration。