简体   繁体   中英

static resource from ${catalina.home} in spring boot war

In my Spring MVC project I had

<mvc:resources mapping="/resources/**" location="/WEB-INF/resources/, file:${catalina.home}/myresources/" />

configured to serve static resources from multiple locations. In Spring Boot however,

@Configuration
public class ResourceConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/", "file:${catalina.home}/myresources/");
    }
}

is not working as expected. Please help.

Spring doesn't read this property ${Catalina.home} directly in your string. But you can use @Value by following way:

@Configuration
public class ResourceConfig implements 
WebMvcConfigurer {
    @Value("${catalina.home}" )
    private String catalinaHome;
    @Override
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/", "file:" + catalinaHome + "/myresources/");
    }
}
    @Configuration
public class ResourceConfig implements WebMvcConfigurer {

    private static final Log LOG = LogFactory.getLog(ResourceConfig.class);

    @Override
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        String catalinaHome;
        try {
            catalinaHome = System.getenv("CATALINA_HOME");
        } catch (Exception e) {
            LOG.error(e);
            catalinaHome = "";
        }
        registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/", "file:" + catalinaHome + "/myresources/");    
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM