需求: 多个房管局房源系统都需要展示户型图, 考虑到图片资源过大(房源共计8w多套), 肯定不能每个系统都复制一份,所以决定将系统部署至同一台服务器,通过一些设置从而共用磁盘图片
import com.app.common.service.DataDictService;
import com.app.ftxh.model.Project;
import com.app.ftxh.service.ProjectService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.List;
/**
* 建立服务器磁盘虚拟路径 用于图片绝对路径展示
* Created by M·JJ on 2020-07-09
*/
@Configuration
@EnableWebMvc
public class WebAppConfig extends WebMvcConfigurerAdapter {
private static final Logger log = LoggerFactory.getLogger(WebAppConfig.class);
/**
* 添加一些虚拟路径的映射
* 对文件的路径进行配置, 创建一个虚拟路径/housePic/** ,
* 即只要在< img src="/housePic/picName.jpg" />即可将本地的d:/pic/picName.jpg展示
*
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
log.info("静态资源配置类触发开始");
ProjectService projectService = new ApplicationContextProvider().getBean(ProjectService.class);
DataDictService dataDictService = new ApplicationContextProvider().getBean(DataDictService.class);
//获取数据字典中的本地图片路径
String prefRealPath = dataDictService.getMapByParentAttributeNameForName("图片路径配置").get("图片路径");//图片文件前置通用路径
List<Project> projectList = projectService.listAll();
if (CollectionUtils.isNotEmpty(projectList)) {
for (Project project : projectList) {
String projectCode = project.getProjectCode();
String realPath = prefRealPath + projectCode + "/";
registry.addResourceHandler("/housePic/" + projectCode + "/**").addResourceLocations("file:" + realPath);
}
}
log.info("静态资源配置类触发成功");
}
}