SpringBoot 정적 자원 설정 원리(소스 코드 분석)

선언:
SpringBoot 시작 은 기본적으로 많은 xxxAutoConfiguration 클래스(자동 설정 클래스)를 불 러 옵 니 다.
그 중에서 SpringMVC 의 대부분 기능 은 WebMvcAutoConfiguration 류 에 집중 되 고 조건 에 따라 ConditionalOnxxx 등록 류 대상 에 집중 된다.WebMvcAutoConfiguration 은 다음 과 같은 ConditionalOnxxx 조건 을 만족 시 키 고 클래스 는 효력 이 발생 하 며 대상 을 용기 에 등록 합 니 다.
在这里插入图片描述
그럼 WebMvcAutoConfiguration 은 용기 에 무엇 을 설정 하 였 습 니까?
WebMvcAutoConfigurationAdapter 정적 내부 클래스
파일 접두사 설정
WebMvcAutoConfiguration 클래스 의 WebMvcAutoConfiguration Adapter 정적 내부 클래스 를 살 펴 보 겠 습 니 다.
在这里插入图片描述
이것 은 설정 클래스 입 니 다.설정 파일 의 속성 과 xxx 가 연결 되 어 있 습 니 다.
다시 보기@EnableConfigurationProperties({WebMvcProperties.class,Resource Properties.class,WebProperties.class})
웹 MvcProperties,ResourceProperties,웹 Properties 의 바이트 파일 을 보 겠 습 니 다.
이 세 가지 종류의 바이트 파일 에 각각 점 을 찍 습 니 다.
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
WebMvc Properties 를 볼 수 있 습 니 다.설정 파일 접두사 spring.mvc 와 연 결 된 것 입 니 다.
리 소스 Properties 는 설정 파일 접두사 spring.resources 와 연 결 됩 니 다.
WebProperties 는 설정 파일 접두사 spring.web 와 연 결 됩 니 다.
2.하나만 구조 기 가 있다.
WebMvcAutoConfigurationAdapter 정적 내부 설정 류 는 매개 변수 가 있 는 구조 기 만 있 습 니 다.어떤 특성 을 가 져 올 까요?
그것 의 구조 기 에 있 는 모든 매개 변수의 값 은 용기 에서 확 정 됩 니 다.

public WebMvcAutoConfigurationAdapter(ResourceProperties resourceProperties, WebProperties webProperties, WebMvcProperties mvcProperties, ListableBeanFactory beanFactory, ObjectProvider<HttpMessageConverters> messageConvertersProvider, ObjectProvider<WebMvcAutoConfiguration.ResourceHandlerRegistrationCustomizer> resourceHandlerRegistrationCustomizerProvider, ObjectProvider<DispatcherServletPath> dispatcherServletPath, ObjectProvider<ServletRegistrationBean<?>> servletRegistrations) {
      this.resourceProperties = (Resources)(resourceProperties.hasBeenCustomized() ? resourceProperties : webProperties.getResources());
      this.mvcProperties = mvcProperties;
      this.beanFactory = beanFactory;
      this.messageConvertersProvider = messageConvertersProvider;
      this.resourceHandlerRegistrationCustomizer = (WebMvcAutoConfiguration.ResourceHandlerRegistrationCustomizer)resourceHandlerRegistrationCustomizerProvider.getIfAvailable();
      this.dispatcherServletPath = dispatcherServletPath;
      this.servletRegistrations = servletRegistrations;
      this.mvcProperties.checkConfiguration();
    }
우 리 는 그것 의 인 자 를 살 펴 보 자.
  • 첫 번 째 매개 변 수 는 ResourceProperties resourceProperties 입 니 다.위 에서 언급 한@Enable ConfigurationProperties({WebMvcProperties.class,ResourceProperties.class,WebProperties.class})에 등 록 된 두 번 째 클래스 입 니 다.spring.resources 와 연 결 된 모든 값 을 가 져 오 는 대상
  • 두 번 째 매개 변 수 는 WebProperties webProperties 입 니 다.위 에서 언급 한@Enable ConfigurationProperties({WebMvcProperties.class,Resource Properties.class,WebProperties.class})에 등 록 된 세 번 째 클래스 입 니 다.spring.web 와 연 결 된 모든 값 을 가 져 오 는 대상
  • 세 번 째 매개 변 수 는 WebMvc Properties mvc Properties 입 니 다.위 에서 언급 한@Enable ConfigurationProperties({WebMvc Properties.class,Resource Properties.class,WebProperties.class})에서 열 린 첫 번 째 클래스 입 니 다.spring.mvc 와 묶 인 모든 값 을 가 져 오 는 대상
  • 입 니 다.
  • 네 번 째 매개 변 수 는 Listable BeanFactory beanFactory 입 니 다.이것 은 Spring 의 beanFactory,즉 우리 의 용기 입 니 다.
  • 다섯 번 째 인 자 는 Object Provider message Converters Provider 입 니 다.모든 HttpMessage Converters
  • 를 찾 습 니 다.
  • 여섯 번 째 인 자 는 Object Providerresource Handler Registration Customizer Provider 입 니 다.자원 프로세서 의 사용자 정의 기 를 찾 습 니 다
  • 일곱 번 째 인 자 는 Object Provider dispatcher ServletPath 입 니 다.dispatcher Servlet 을 찾 아서 처리 할 수 있 는 경로
  • 와 같 습 니 다.
  • 여덟 번 째 인 자 는 Object Provider입 니 다.servletRegistrations,응용 프로그램 에 등 록 된 원생 의 Servlet,Filter 등
  • 구조 기 가 초기 화 된 후,우 리 는 이미 모든 물건 을 용기 에서 가 져 왔 다.
    3.소스 코드 분석 addResource Handlers 방법
    모든 자원 처리 기본 규칙 은 addResource Handlers 방법 에 있 습 니 다.다음 과 같 습 니 다.
    
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
          if (!this.resourceProperties.isAddMappings()) {
            logger.debug("Default resource handling disabled");
          } else {
            Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
            CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
            if (!registry.hasMappingForPattern("/webjars/**")) {
              this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl).setUseLastModified(this.resourceProperties.getCache().isUseLastModified()));
            }
    
            String staticPathPattern = this.mvcProperties.getStaticPathPattern();
            if (!registry.hasMappingForPattern(staticPathPattern)) {
              this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl).setUseLastModified(this.resourceProperties.getCache().isUseLastModified()));
            }
    
          }
        }
    1.정적 자원 의 경로 맵 사용 하지 않 기
    기본 규칙 이 어떻게 작 동 하 는 지 정지점 을 두 고 보 겠 습 니 다.먼저 resourcePropertoes 의 isAddMappings()방법 을 호출 합 니 다.
    在这里插入图片描述
    this.resourcePropertoes 의 isAddMappings()방법 이 true 인지 아 닌 지 판단 합 니 다.
  • this.resourcePropertoes 우리 가 방금 2 에서 구조 기 를 강의 할 때 말 한 ResourceProperties resourceProperties resourceProperties 는 바로 우리 가 위 에서 언급 한@EnableConfigurationProperties({WebMvcProperties.class,ResourceProperties.class,WebProperties.class})에 등 록 된 두 번 째 클래스 입 니 다.spring.resources 와 연 결 된 모든 값 을 가 져 오 는 대상
  • isAddMappings()방법 은 this.addMappings 의 값 을 되 돌려 줍 니 다.다음 과 같 습 니 다.
  • 在这里插入图片描述
    즉,우 리 는 addMappings 의 값 이 false 인지 true 인지 설정 함으로써 이 if 문 구 를 실행 할 수 있 습 니 다.
    설정 파일 에서 설정 할 수 있 습 니 다:
    在这里插入图片描述
    기본 값 은 true 입 니 다.false 라면 if 구문 에 들 어가 서 실행logger.debug("Default resource handling disabled");한 후에 이 방법 을 끝 냅 니 다.else 의 모든 설정 이 유효 하지 않 습 니 다.
    在这里插入图片描述
    else 의 어떤 설정/webjars/**을 어디로 찾 는 지 등 일부 규칙 이 적용 되 지 않 습 니 다.
    즉,우 리 는 설정add-mappings: false을 통 해 정적 자원 의 경로 맵 을 사용 하지 않 는 다 는 것 이다.
    사용 하지 않 으 면 모든 정적 자원 에 접근 할 수 없습니다.
    addMappings 의 값 이 true 라면 if 구문 에 들 어가 지 않 고 else 구문 에 들 어가 면 else 문장의 내용 이 모두 실 행 됩 니 다.다음은 정적 자본 규칙 을 어떻게 설정 하 는 지 보 겠 습 니 다.
    2.소스 코드 분석 webjars 의 바 텀 규칙
    else 구문 에 들 어가 면 첫 번 째 줄 은Duration cachePeriod = this.resourceProperties.getCache().getPeriod();입 니 다.resourceProperties 에서 캐 시 에 관 한 값 을 가 져 옵 니 다.Yml 프로필 에 이 값 을 설정 합 니 다:
    在这里插入图片描述
    캐 시 시간 은 초 단위 입 니 다.다음 과 같 습 니 다.
    在这里插入图片描述
    우리 의 모든 정적 자원 은 기본적으로 몇 초 동안 캐 시 할 수 있 습 니까?
    우리 debug 는 이어서 아래로 내 려 갑 니 다.cachePeriod 에서 방금 Yml 에 설 치 된 6666 을 찾 았 습 니 다.나중에 우리 의 브 라 우 저 는 우리 의 정적 자원 캐 시 6666 초 를 찾 을 것 입 니 다.
    在这里插入图片描述
    debug 는 이어서 내 려 갑 니 다.우 리 는 등록"/webjars/**"이라는 규칙 이 있 는 곳 에 도 착 했 습 니 다.
    
    if (!registry.hasMappingForPattern("/webjars/**")) {
              this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl).setUseLastModified(this.resourceProperties.getCache().isUseLastModified()));
            }
    즉,우리 가 방문/webjars아래 의 모든 요청 은 우리 의classpath:/META-INF/resources/webjars/경 로 를 찾 고 그 중에서 정적 자원 의 캐 시 시간 도 6666 초 로 설정 했다.
    jquery 를 예 로 들 면,왜 우리 가 jquery 를 가 져 온 후에,우 리 는/webjars/jquery/3.5.1/jquery.js 만 방문 하면/META-INF/resources/webjars/jquery/3.5.1/jquery.js 에 접근 할 수 있 습 니까?다음 과 같 습 니 다:
    在这里插入图片描述
    在这里插入图片描述
    캐 시 시간 도 브 라 우 저 에서 6666 초 로 볼 수 있 습 니 다.
    在这里插入图片描述
    3.원본 코드 분석 기본 정적 자원 경로 의 바 텀 규칙
    우 리 는 else 에서 이어서 debug 를 내 려 가 고,이어서 우 리 는 mvc Properties 속성 으로 getStatic PathPattern()방법 을 호출 합 니 다.
    在这里插入图片描述
  • this.mvc Properties 우리 가 방금 2 에서 구조 기 를 강의 할 때 말 한 WebMvc Properties mvc Properties 는 바로 우리 가 위 에서 언급 한@Enable ConfigurationProperties({WebMvc Properties.class,Resource Properties.class,WebProperties.class})에 등 록 된 첫 번 째 클래스 입 니 다.spring.mvc 와 연 결 된 모든 값 의 대상
  • 을 가 져 옵 니 다.
  • getStaticPathPattern()방법,이 방법 은 staticPathPattern 의 값 을 되 돌려 줍 니 다.다음 과 같 습 니 다.
  • 在这里插入图片描述
    staticPathPattern 의 이 값 은 설정 파일 에서 설정 할 수 있 습 니 다.기본 값 은/**입 니 다.다음 과 같 습 니 다.
    在这里插入图片描述
    우리 도 접 두 사 를/resource/**로 설정 할 수 있 습 니 다.다음 과 같 습 니 다.
    在这里插入图片描述
    debug 는 이어서 아래로 내 려 갑 니 다.그 다음 에 호출 하 는 방법 은 위의webjars과 같은 방법 입 니 다.다만 매개 변 수 는 다 릅 니 다.
    在这里插入图片描述
    다음은 코드 를 구체 적 으로 보 겠 습 니 다.
    
    String staticPathPattern = this.mvcProperties.getStaticPathPattern();
            if (!registry.hasMappingForPattern(staticPathPattern)) {
              this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl).setUseLastModified(this.resourceProperties.getCache().isUseLastModified()));
            }
    방금 접 두 사 를 staticPathPattern 으로 받 은 후 hasMappingForPattern 방법 에 실제 참조 로 전송 합 니 다.등록 이라는 규칙 은 방금 Yml 에 접 두 사 를/resource/**로 설정 하 였 습 니 다.즉,방문/resource/**아래 의 모든 요청 이 우리 의this.resourceProperties.getStaticLocations()경 로 를 찾 았 습 니 다.그 중에서 도 정적 자원 의 캐 시 시간 은 6666 초 입 니 다.this.resourceProperties.getStaticLocations()방법 이 되 돌아 오 는 값 은 무엇 입 니까?우리 눌 러 서 들 어가 보 자.
    在这里插入图片描述 this.resourceProperties.getStaticLocations()돌아 온 것 은 this.staticLocations 입 니 다.이 staticLocations 정 의 는 다음 과 같 습 니 다.
    在这里插入图片描述
    문자열 배열 을 볼 수 있 습 니 다.무 참 구조 기 에서 초기 화 되 었 습 니 다.초기 화 된 값 은 CLASSPATH 입 니 다.RESOURCE_LOCATIONS 상수,상수 의 값 은:
    “classpath:/META-INF/resources/”, “classpath:/resources/”, “classpath:/static/”, "classpath:/public/“。이것 은 정적 자원 경로 가 왜 이 네 개의 경로 로 기본 적 으로 되 어 있 는 지 설명 한다.
    이곳 을 보고 당신 은 문득 크게 깨 달 았 습 니까?
    스프링 부 트 정적 자원 설정 원리(원본 분석)에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.스프링 부 트 정적 자원 설정 에 관 한 더 많은 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 찾 아 보 세 요.앞으로 도 많은 지원 을 바 랍 니 다!

    좋은 웹페이지 즐겨찾기