在SpringBoot Application

时间:2016-02-09 11:21:29

标签: spring spring-boot

我想动态添加一些资源(意味着在Jar应用程序运行时),但具有挑战性的部分是:我无法在运行时更改Jar内容,所以我需要创建一些其他空间作为资源目录和试着从那里取。 (这是最佳实践吗?如果没有,请提供解决方案)

示例: 我的春季启动应用程序的Jar位于文件系统中:

/home/my_spring_project/target/myproject.jar

要运行java -jar /home/my_spring_project/target/myproject.jar

我保留了运行时上传图片资源

/home/my_spring_project/uploads/user1_image.jpg

但我无法将/home/my_spring_project/uploads目录设为资源目录

这是我的spring应用程序代码,我试图分别指定资源目录:

@Configuration
public class StaticResourceConfiguration extends WebMvcConfigurerAdapter
{

private static final String[] RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/" };

private static final String UPLOAD_DIR = "/uploads"; //currently application is mapping to base_dir of project i.e. /home/my_spring_project

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
{
    if (!registry.hasMappingForPattern("/**"))
    {
        registry.addResourceHandler("/**").addResourceLocations(RESOURCE_LOCATIONS);
    }
    registry.addResourceHandler("/uploads/**").addResourceLocations(UPLOAD_DIR);
}

}

我还需要由spring应用程序选择的bydefault资源目录,因为我将保留前端模块。

我只想添加一个除JAR之外的目录,我可以在运行时上传任何文件。因此,我不需要更改JAR包装中的内容。

先谢谢

1 个答案:

答案 0 :(得分:1)

当我提供绝对路径时它起作用,所以解决方法是,我们可以将运行时参数传递给我们的应用程序:

@Configuration
public class StaticResourceConfiguration extends WebMvcConfigurerAdapter
{

@Value("${upload.location}")
private String uploadLocation;

private static final String[] RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/" };

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry)
  {
    if (!registry.hasMappingForPattern("/**"))
    {
        registry.addResourceHandler("/**").addResourceLocations(RESOURCE_LOCATIONS);
    }
    registry.addResourceHandler("/uploads/**").addResourceLocations(uploadLocation);
  }
}

因此,在运行应用程序时,我们需要提供如下参数值:

java -jar /home/my_spring_project/target/myproject.jar --upload.location=file:/home/my_spring_project/uploads

感谢@Brian Clozel