Reputation: 288
Below code works fine if file location is resources folder but when file location is outside the project directory like(c:\file.json) it fails. How can we load file from outside project directory.
@Bean
public UserInfo readFile() {
String fileName="prop.json";
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
try {
UserInfo info= new ObjectMapper(new JsonFactory()).readValue(file, UserInfo.class);
} catch (Exception e) {
}
return info;
}
Upvotes: 1
Views: 467
Reputation: 220
You should create a Configuration class that implements WebMvcConfigurer and override the addResourceHadndler Method to add new resource to spring context.
@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer{
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// register you resource here
}
}
Upvotes: 1