Spring Boot集成AclPermissionEvaluator触发IllegalStateException:未设置ServletContext
Hey there, I’ve dealt with this exact hiccup before when setting up Spring Security ACL in a Spring Boot app—let’s walk through the most practical fixes to get your app up and running smoothly.
The root cause matches your suspicion perfectly: some bean tied to Spring Security ACL is getting initialized before the ServletContext is ready during Spring Boot’s auto-config flow. Here’s how to fix it:
Lazy-load beans that depend on ServletContext
If you have ACL-related beans (like expression handlers or filter setups) that need access to the ServletContext, mark them or their dependencies with@Lazy. This tells Spring to hold off creating them until they’re actually needed—by which point the ServletContext will be fully initialized. Example:@Configuration public class AclConfig { @Bean @Lazy public MethodSecurityExpressionHandler aclMethodSecurityHandler() { DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler(); // Add your ACL-specific configuration here return handler; } }Inject ServletContext directly into bean methods
When defining beans that require the ServletContext, let Spring inject it as a method parameter instead of trying to fetch it manually. Spring will automatically ensure the ServletContext exists before creating this bean:@Bean public FilterRegistrationBean<AclFilter> aclFilterRegistration(ServletContext servletContext) { FilterRegistrationBean<AclFilter> registration = new FilterRegistrationBean<>(); registration.setFilter(new AclFilter()); registration.setServletContext(servletContext); // Configure other filter properties (url patterns, order, etc.) return registration; }Restrict ACL config to web environments
Add@ConditionalOnWebApplicationto your ACL configuration class. This ensures the entire configuration is only processed when Spring Boot detects a web environment, guaranteeing the ServletContext is available:@Configuration @ConditionalOnWebApplication public class AclWebSecurityConfig { // All your ACL-related bean definitions live here }Check for early bean references
If you’re referencing ACL beans in your main application class or other early-loaded configurations, add@Lazyto those references too. For example:@SpringBootApplication public class MyApp { @Autowired @Lazy private AclService aclService; // ... rest of your application setup }
Give these steps a shot—one of them will almost certainly resolve the No ServletContext set error. If you’re still stuck, sharing a snippet of your ACL configuration class would help narrow things down further!
内容的提问来源于stack exchange,提问作者moritzrupp

