1. 程式人生 > 實用技巧 >SpringBoot外部靜態資源的訪問

SpringBoot外部靜態資源的訪問

springboot專案訪問jar外部靜態資源,html舉例子

簡單描述,在啟動類中實現WebMvcConfigurer介面,實現其addResourceHandlers方法即可。

@SpringBootApplication
@EnableSwagger2
@EnableSwaggerBootstrapUI
@MapperScan("com.job.mapper")//掃描mapper包
@PropertySource(value = "classpath:config/app.properties", encoding = "UTF-8")
public class Application implements CommandLineRunner, WebMvcConfigurer {

    private final Logger logger = LoggerFactory.getLogger(Application.class);

    @Value("${html.agreement}")
    // html.agreement=/agreement
    private String agreement;

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

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:META-INF/resources/")
                .addResourceLocations("classpath:/resources/")
                .addResourceLocations("classpath:/public/")
                .addResourceLocations("classpath:/static/")
                .addResourceLocations("file:" + agreement + File.separator);
    }

    @Override
    public void run(String... args) throws Exception {
        logger.info("Server started successfully...");
    }
}