Spring
스프링 부트 Resource 파일 데이터로 가져오기
기록만이살길
2020. 6. 17. 21:09
반응형
스프링 부트 Resource 파일 얻기
이 블로그에서는 Spring에서 리소스 파일 (속성 파일뿐만 아니라)을 얻는 방법을 보여줍니다. maven build 프로젝트를 사용하면 모든 리소스 파일이 resources 폴더에 저장됩니다.
프로젝트 구조
├─main
│ ├─java
│ │ └─com
│ │ └─henryxi
│ │ └─resources
│ │ ResourcesController.java
│ │
│ └─resources
│ application.properties
│ test.txt
│
└─test
└─javapom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
</dependencies>
resourcesController.java
@RestController
@EnableAutoConfiguration
public class ResourcesController {
@Autowired
private ResourceLoader resourceLoader;
@RequestMapping(value = "/get-resources", method = RequestMethod.GET)
public String getResources() throws IOException {
String content = IOUtils.toString(resourceLoader.getResource("classpath:test.txt").getInputStream());
return "the content of resources:" + content;
}
public static void main(String[] args) {
SpringApplication.run(ResourcesController.class, args);
}
}
이 클래스를 실행하고 다음과 같이 http : // localhost : 8080 / get-resources 출력에 액세스 하십시오.
the content of resources:this is a test file약 classpath
Maven 프로젝트에서 모든 리소스는 클래스 폴더에 복사됩니다 (리소스 폴더를 지정하지 않은 경우). classpathTomcat에는 "ResourceLoader컨트롤러에 주입 한 후 resourceLoader.getResource("classpath:test.txt")에서 "test.txt"파일을 찾으십시오
반응형