2
0
Эх сурвалжийг харах

Default RequestCache as @Bean

Fixes: gh-5583
Rob Winch 7 жил өмнө
parent
commit
7b2b1a877d

+ 17 - 0
config/src/main/java/org/springframework/security/config/annotation/web/configurers/RequestCacheConfigurer.java

@@ -19,6 +19,8 @@ import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
 
+import org.springframework.beans.factory.NoSuchBeanDefinitionException;
+import org.springframework.context.ApplicationContext;
 import org.springframework.http.MediaType;
 import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
 import org.springframework.security.config.annotation.web.builders.HttpSecurity;
@@ -113,11 +115,26 @@ public final class RequestCacheConfigurer<H extends HttpSecurityBuilder<H>> exte
 		if (result != null) {
 			return result;
 		}
+		result = getBeanOrNull(RequestCache.class);
+		if (result != null) {
+			return result;
+		}
 		HttpSessionRequestCache defaultCache = new HttpSessionRequestCache();
 		defaultCache.setRequestMatcher(createDefaultSavedRequestMatcher(http));
 		return defaultCache;
 	}
 
+	private <T> T getBeanOrNull(Class<T> type) {
+		ApplicationContext context = getBuilder().getSharedObject(ApplicationContext.class);
+		if (context == null) {
+			return null;
+		}
+		try {
+			return context.getBean(type);
+		} catch (NoSuchBeanDefinitionException e) {
+			return null;
+		}
+	}
 	@SuppressWarnings("unchecked")
 	private RequestMatcher createDefaultSavedRequestMatcher(H http) {
 		ContentNegotiationStrategy contentNegotiationStrategy = http

+ 22 - 0
config/src/test/java/org/springframework/security/config/annotation/web/configurers/FormLoginConfigurerTests.java

@@ -19,6 +19,7 @@ package org.springframework.security.config.annotation.web.configurers;
 import org.junit.Rule;
 import org.junit.Test;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
 import org.springframework.security.config.annotation.web.builders.HttpSecurity;
 import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
 import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@@ -69,4 +70,25 @@ public class FormLoginConfigurerTests {
 					.requestCache(this.requestCache);
 		}
 	}
+
+	@Test
+	public void requestCacheAsBean() throws Exception {
+		this.spring.register(RequestCacheBeanConfig.class,
+				AuthenticationTestConfiguration.class).autowire();
+
+		RequestCache requestCache = this.spring.getContext().getBean(RequestCache.class);
+
+		this.mockMvc.perform(formLogin())
+				.andExpect(authenticated());
+
+		verify(requestCache).getRequest(any(), any());
+	}
+
+	@EnableWebSecurity
+	static class RequestCacheBeanConfig {
+		@Bean
+		RequestCache requestCache() {
+			return mock(RequestCache.class);
+		}
+	}
 }