SpringBoot 정적 자원 설정 원리(소스 코드 분석)
12538 단어 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();
}
우 리 는 그것 의 인 자 를 살 펴 보 자.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 인지 아 닌 지 판단 합 니 다.
즉,우 리 는 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()방법 을 호출 합 니 다.
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/“。이것 은 정적 자원 경로 가 왜 이 네 개의 경로 로 기본 적 으로 되 어 있 는 지 설명 한다.
이곳 을 보고 당신 은 문득 크게 깨 달 았 습 니까?
스프링 부 트 정적 자원 설정 원리(원본 분석)에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.스프링 부 트 정적 자원 설정 에 관 한 더 많은 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 찾 아 보 세 요.앞으로 도 많은 지원 을 바 랍 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
【Java・SpringBoot・Thymeleaf】 에러 메세지를 구현(SpringBoot 어플리케이션 실천편 3)로그인하여 사용자 목록을 표시하는 응용 프로그램을 만들고, Spring에서의 개발에 대해 공부하겠습니다 🌟 마지막 데이터 바인딩에 계속 바인딩 실패 시 오류 메시지를 구현합니다. 마지막 기사🌟 src/main/res...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.