Spring Content,一种在测试环境中用图像填充数据库的便捷方法

问题描述

要存储图像,我正在使用Spring Content JPA策略。 我的测试配置文件具有HsqlDB内存实现。 有没有更方便的方法来用图像填充数据库? 现在,我有一个解决方案:创建一个包含图像的文件夹,然后 在启动时手动上传它们。据我了解,要摆脱图像文件夹,我可以将它们上传sqlite,然后从中获取数据,但是也许有更好的方法吗?

CarrentalApplication

@SpringBootApplication
@EnableJpaRepositories
@EnableJpaStores
public class CarrentalApplication {
    private static final String IMAGE_FOLDER = "classpath:static/img/test-cars/";
    private final Map<Integer,String> cars = new HashMap<>() {{
        put(100010,"merc_benz");
        put(100011,"volvo_s60");
        put(100012,"suz_swift");
        put(100013,"volks16v");
        put(100014,"ford150");
        put(100015,"lambo610");
        put(100016,"bmvx5");
        put(100017,"audis6");
    }};

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

    @Bean
    public CommandLineRunner uploadImages(CarService carService,CarRepository carRepository,CarImageStore imageStore) {
        return (args) -> cars.forEach((carId,name) -> {
            try {
                Car car = carService.get(carId);
                File file = ResourceUtils.getFile(IMAGE_FOLDER + name + ".jpg");
                FileInputStream input = new FileInputStream(file);
                imageStore.setContent(car,input);
                carRepository.save(car);
            } catch (Exception e) {
                e.printstacktrace();
            }
        });
    }
}

CarImageStore

@StoreRestResource(path = "data")
@Repository
public interface CarImageStore extends ContentStore<Car,String> {
}

汽车内容字段:

@ContentId
private String contentId;

@ContentLength
private Long contentLength = 0L;

@MimeType
private String mimeType = "text/plain";

解决方法

另一种方法是将图像移到类路径上;即进入/src/test/resources(假设Maven)并从那里加载它们:

imageStore.setContent(car,this.getClass().getResourceAsStream("/" + name + ".jpg"));