sourcetip

스프링 부트 액세스 정적 리소스가 없습니다.scr/main/resources

fileupload 2023. 2. 13. 20:38
반응형

스프링 부트 액세스 정적 리소스가 없습니다.scr/main/resources

Spring Boot 어플리케이션을 만들고 있습니다.시작 시 XML 파일(countries.xml)을 해석해야 합니다.문제는 어디에 둬야 접속할 수 있는지 모르겠다는 것입니다.내 폴더 구조는

ProjectDirectory/src/main/java
ProjectDirectory/src/main/resources/countries.xml

처음에는 src/main/resources에 넣으려고 했는데, 파일(counts.xml)을 작성하려고 하면 NPE가 표시되고 스택 트레이스에는 Project Directory에 파일이 표시됩니다(따라서 src/main/resources/는 추가되지 않습니다).파일(resources/countries.xml)을 작성하려고 했는데 경로가 Project Directory/resources/countries.xml과 비슷합니다(따라서 src/main은 추가되지 않았습니다).

이것을 추가하려고 했지만 아무 결과도 없었다.

@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
    super.addResourceHandlers(registry);
}

src/main/을 수동으로 추가할 수 있는 것은 알고 있습니다만, 왜 정상적으로 동작하지 않는지 알고 싶습니다.Resource Loader를 사용한 예도 시도해 보았습니다만, 결과는 없었습니다.

문제가 무엇인지 누가 제안해 줄 수 있나요?

업데이트: 향후 참조를 위해 프로젝트 구축 후 파일 접근에 문제가 발생하여 파일을 Input Stream으로 변경하였습니다.

InputStream is = new ClassPathResource("countries.xml").getInputStream();

Spring 유형 ClassPathResource만 사용하십시오.

File file = new ClassPathResource("countries.xml").getFile();

이 파일이 클래스 패스에 있는 한 스프링이 찾을 거야이 경우src/main/resources개발 및 테스트 중에 사용합니다.프로덕션에서는 현재 실행 중인 디렉토리일 수 있습니다.

편집: 파일이 Fat JAR에 있는 경우 방법은 작동하지 않습니다.이 경우 다음을 사용해야 합니다.

InputStream is = new ClassPathResource("countries.xml").getInputStream();

Spring Boot 어플리케이션 사용 시 클래스 패스리소스를 취득하는 것은 어렵습니다.resource.getFile()같은 문제에 직면했을 때와 같이, JAR로서 전개되고 있는 경우.이 검색은 클래스 경로의 모든 위치에 있는 리소스를 검색하는 스트림을 사용하여 해결됩니다.

이하에 같은 코드 스니펫을 나타냅니다.

ClassPathResource classPathResource = new ClassPathResource("fileName");
InputStream inputStream = classPathResource.getInputStream();
content = IOUtils.toString(inputStream);

classpath 내의 파일을 가져오려면 다음 절차를 수행합니다.

Resource resource = new ClassPathResource("countries.xml");
File file = resource.getFile();

시작 시 파일을 읽으려면시작 시@PostConstruct:

@Configuration
public class ReadFileOnStartUp {

    @PostConstruct
    public void afterPropertiesSet() throws Exception {

        //Gets the XML file under src/main/resources folder
        Resource resource = new ClassPathResource("countries.xml");
        File file = resource.getFile();
        //Logic to read File.
    }
}

다음은 Spring Boot App 부팅 시 XML 파일을 읽기 위한 작은 예입니다.

스프링 부츠를 사용하고 있기 때문에, 간단하게 사용할 수 있습니다.

File file = ResourceUtils.getFile("classpath:myfile.xml");

다음 구조를 사용해야 합니다.

InputStream in = getClass().getResourceAsStream("/yourFile");

파일 이름 앞에 이 슬래시를 추가해야 합니다.

다음 코드를 사용하여 리소스 폴더에서 문자열의 파일을 읽을 수 있습니다.

final Resource resource = new ClassPathResource("public.key");
String publicKey = null;
try {
     publicKey = new String(Files.readAllBytes(resource.getFile().toPath()), StandardCharsets.UTF_8);
} catch (IOException e) {
     e.printStackTrace();
}

Spring Boot을 사용하고 있습니다.이 문제의 해결방법은

"src/main/resources/myfile.extension"

도움이 됐으면 좋겠는데

왜냐하면 java.net.「URL은, 모든 종류의 저레벨의 자원을 처리하기에 적합하지 않습니다」라고 Spring은 org.springframework.core.io를 도입했습니다.자원리소스에 액세스하려면 @Value 주석 또는 ResourceLoader 클래스를 사용합니다.@자동화된 프라이빗 Resource Loader resource Loader;

@공용 무효 실행(String...)을 덮어씁니다.args) 예외 {

    Resource res = resourceLoader.getResource("classpath:thermopylae.txt");

    Map<String, Integer> words =  countWords.getWordsCount(res);

    for (String key : words.keySet()) {

        System.out.println(key + ": " + words.get(key));
    }
}

언급URL : https://stackoverflow.com/questions/36371748/spring-boot-access-static-resources-missing-scr-main-resources

반응형