在SpringBoot中获取resource路径有多种方式
在SpringBoot中获取resource路径有多种方式:
- 使用
ClassPathResource
类:可以通过ClassPathResource
类获取classpath下的资源路径。例如,可以使用以下代码获取classpath下的config.properties
文件路径:
ClassPathResourceresource=newClassPathResource("config.properties");
Stringpath=resource.getFile().getAbsolutePath();
ResourceLoader
接口:通过注入ResourceLoader
接口,可以使用getResource
方法获取资源路径。例如,可以使用以下代码获取classpath下的config.properties
文件路径:@Autowired
privateResourceLoaderresourceLoader;
publicvoidgetResourcePath(){
Resourceresource=resourceLoader.getResource("classpath:config.properties");
Stringpath=resource.getFile().getAbsolutePath();
}
@Value
注解:可以使用@Value
注解将资源路径注入到变量中。例如,可以使用以下代码获取classpath下的config.properties
文件路径:@Value("classpath:config.properties")
privateResourceresource;
publicvoidgetResourcePath(){
Stringpath=resource.getFile().getAbsolutePath();
}
无论使用哪种方式,都可以获取到classpath下资源的路径。
版权声明
本文仅代表作者观点,不代表博信信息网立场。