SpringBoot调用项目下静态资源的方法

2021-12-18 965点热度 0人点赞 0条评论

Q

SpringBoot项目中,如果要调取项目下的静态文件资源,要怎么做?

A

如果静态资源放在src/main/resources下,如图:

调用方式,以Service为例,SystemServiceImpl.java如下

@Service("systemService")
@Transactional(readOnly = false)
@Repository
public class SystemServiceImpl implements ISystemService {

    @Resource(name = "systemDao")
    private ISystemDao systemDao;

    @Autowired
    private Environment env;

    @Value(value = "classpath:/assets/default_portrait.jpg")
    private org.springframework.core.io.Resource defaultPortraitJPG;

    // 其他代码省略
    public void someMethod() {
        // 读取静态文件default_portrait.jpg
        // defaultPortraitJPG 这个Resource方法有getFile() getInputStream()
        // 例如 byte[] data = IOUtils.toByteArray(defaultPortraitJPG.getInputStream())
    }
}

如果你还有MVC架构,静态资源放在src/main/webapp/WEB-INF/下,那么这样调用

@Value(value = "/WEB-INF/templates/class_checkin.html")
private org.springframework.core.io.Resource clazzCheckinHtml;

 

admin

这个人很懒,什么都没留下

文章评论

您需要 登录 之后才可以评论