Обновление до Shiro 1.6.0 с версии 1.4.2, вызывающее java.lang.Исключение IllegalStateException: нет набора ServletContext

#shiro

#shiro

Вопрос:

Запуск при загрузке Spring 2.3.3 .. попытался обновить Shiro с 1.4.2 до 1.5.3, затем до 1.6.0 и получил следующую трассировку стека при запуске (встроенный сервер в Eclipse)

 43:14.333 [main] ERROR o.s.boot.SpringApplication - Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'resourceHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: No ServletContext set
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:655)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:635)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1336)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1176)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:556)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:897)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:879)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:551)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226)

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: No ServletContext set
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:650)
    ... 20 common frames omitted
Caused by: java.lang.IllegalStateException: No ServletContext set
    at org.springframework.util.Assert.state(Assert.java:76)
    at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.resourceHandlerMapping(WebMvcConfigurationSupport.java:534)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
    ... 21 common frames omitted
  

В Shiro 1.4.2 проблем нет… Примечания к выпуску на GitHub не обновлялись, поэтому не уверен, что вызывает проблему в последней версии.

Зависимости Shiro:

 <shiro.version>1.6.0</shiro.version>
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-spring-boot-web-starter</artifactId>
        <version>${shiro.version}</version>
    </dependency>
    
    <dependency>
        <groupId>com.github.theborakompanioni</groupId>
        <artifactId>thymeleaf-extras-shiro</artifactId>
        <version>2.0.0</version>
    </dependency>
  

Конфигурация / компоненты:

 @Configuration
public class ShiroConfig {

private static String LOGGING_PREFIX = "[ShiroConfig] ";
protected static final Logger logger = LoggerFactory.getLogger(ShiroConfig.class);

@Bean
public ShiroFilterChainDefinition shiroFilterChainDefinition() {
    DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();
    chainDefinition.addPathDefinition("/css/**", "anon");
    chainDefinition.addPathDefinition("/js/**", "anon");
    chainDefinition.addPathDefinition("/images/**", "anon");
    chainDefinition.addPathDefinition("/signin.html", "authc");
    chainDefinition.addPathDefinition("/secure/actuator/health", "anon");
    chainDefinition.addPathDefinition("/secure/nomination/**", "authc,roles[nominator]");
    chainDefinition.addPathDefinition("/secure/review/**", "authc,anyRoles[reviewer,nationalreviewer]");
    chainDefinition.addPathDefinition("/secure/actuator/**", "authc,roles[sysadmin]");
    chainDefinition.addPathDefinition("/secure/sysadmin/**", "authc,roles[sysadmin]");
    chainDefinition.addPathDefinition("/secure/**", "authc");

    return chainDefinition;
}

@Bean(name = "hashService")
public HashService hashService() {
    DefaultHashService hashService = new DefaultHashService();
    hashService.setHashAlgorithmName("SHA-512");
    hashService.setHashIterations(50000);
    hashService.setPrivateSalt(new SimpleByteSource("xxxxxxxx"));
    return hashService;
}

@Bean(name = "passwordService")
public PasswordService passwordService() {
    DefaultPasswordService passwordService = new DefaultPasswordService();
    passwordService.setHashService(hashService());
    return passwordService;
}

@Bean(name = "passwordMatcher")
public PasswordMatcher passwordMatcher() {
    PasswordMatcher matcher = new PasswordMatcher();
    matcher.setPasswordService(passwordService());
    return matcher;
}

@Bean
public Realm realm() {
    CustomRealm realm = new CustomRealm();
    realm.setCredentialsMatcher(passwordMatcher());
    realm.setCachingEnabled(true);
    return realm;
}

@Bean(name = "authenticationListener")
public AuthenticationListener authenticationListener() {
    return new AuthenticationListenerImpl();
}

@Bean(name = "cacheManager")
public CacheManager cacheManager() {
    return new MemoryConstrainedCacheManager();
}

@Bean
@DependsOn(value = "lifecycleBeanPostProcessor")
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
    DefaultAdvisorAutoProxyCreator proxy = new DefaultAdvisorAutoProxyCreator();
    proxy.setProxyTargetClass(true);
    return proxy;
}

@Bean
public Authenticator authenticator() {
    ModularRealmAuthenticator authenticator = new ModularRealmAuthenticator();
    List<AuthenticationListener> listeners = new ArrayList<AuthenticationListener>();
    listeners.add(authenticationListener());
    authenticator.setAuthenticationListeners(listeners);
    return authenticator;

}

@Bean
public Filter anyRoles() {
    return new AnyOfRolesAuthorizationFilter();
}
  

}

Комментарии:

1. Смогли ли вы устранить эту проблему? Недавно был выпущен Shiro 1.6.0.

2. @Ben та же проблема в 1.6.0…

3. Не могли бы вы, пожалуйста, добавить shiro-части вашего pom.xml файла сборки или gradle к вопросу? Пожалуйста, также добавьте любые компоненты @Configuration, которые у вас могут быть.

4. Спасибо @Ben, вопрос обновлен с помощью Shiro deps и конфигурации.