복붙노트

[SPRING] 스프링 3.1에서 와일드 카드를 사용하여 XML 리소스 파일을로드하는 방법

SPRING

스프링 3.1에서 와일드 카드를 사용하여 XML 리소스 파일을로드하는 방법

Spring Maven 프로젝트에 여러 모듈의 오류 정의가 포함 된 xml 파일을로드하려고합니다. 파일을로드 한 다음 JAXB unmasheller에 전달하고 싶습니다.

이것은 내가 지금까지 한 일이다.

String path = "classpath*:/**/definitions/error-definition.xml";
ClassPathResource resource = new ClassPathResource(path);
unmarshaller.unmarshall(resource);

내 리소스 파일의 위치는 다음과 같습니다.

src / main / resource / module1 / definitions / error-definition.xml

src/main/resource/module2/definitions/error-definition.xml

이것은 나에게 다음과 같은 오류를 준다.

java.io.FileNotFoundException: class path resource [classpath*:/**/definitions/error-definition.xml] cannot be resolved to URL because it does not exist

하지만 다음과 같이 경로를 변경하면

 String path = "/module1/definitions/error-definition.xml";

그것은 작동합니다.

다음은 내가 행운을 가지고 시도한 다른 와일드 카드이다.

String paths = "classpath:/**/definitions/error-definition.xml";
String paths = "classpath*:error-definition.xml";
String paths = "classpath*:*.xml";

내가 원하는 것은 와일드 카드를 사용하여 src / main / resource 아래의 모든 폴더에서 xml 파일을 가져 오는 것입니다.

나는 몇 가지 이전의 SO 답변을 언급했으나 여전히 잘못된 일을 파악하지 못했습니다.

해결법

  1. ==============================

    1.리소스를로드하려면 ResourceLoader를 클래스에 삽입하십시오. ResourceLoaderAware를 구현하거나 ResourceLoader 유형의 필드에 @Autowired를 주석으로 추가하여이 작업을 수행 할 수 있습니다.

    리소스를로드하려면 ResourceLoader를 클래스에 삽입하십시오. ResourceLoaderAware를 구현하거나 ResourceLoader 유형의 필드에 @Autowired를 주석으로 추가하여이 작업을 수행 할 수 있습니다.

    public class YourClass {
    
        @Autowired
        private ResourceLoader rl;
    
    }
    

    이제 ResourceLoader를 사용하여 ResourcePatternUtils를 사용하여 실제로 리소스를로드 할 수 있습니다.

    public Resource[] loadResources() {
        return ResourcePatternUtils.getResourcePatternResolver(rl).getResources("classpath:/directory/**/*-context.xml);
    
    }
    
  2. from https://stackoverflow.com/questions/23100813/how-to-load-xml-resource-file-using-wild-card-in-spring-3-1 by cc-by-sa and MIT license