我想在用户请求的时候,获取二级域名,并注册,然后想到处都能使用。
于是,写了下面的代码,希望在每个session产生的时候,能注册一个subDomain的对象,
然后在一个interceptor中修改subDomain实例的值,
从而使别的注入的地方能取到subDomain的值,
但是报错了。
@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
@Bean
@Scope("session")
public SubDomain subDomain(){
return new SubDomain();
}
}
@Service
public class UserService {
@Autowired
private SubDomain subDomain;
}
错误信息如下
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.exa.as.config.SubDomain com.exa.as.service.UserService.subDomain; nested exception is java.lang.IllegalStateException: No Scope registered for scope 'session'
是不是我缺少配置了?
没有session scope? 注意区分web相关的scope。
/** * Specifies the scope to use for the annotated component/bean. * @see ConfigurableBeanFactory#SCOPE_SINGLETON * @see ConfigurableBeanFactory#SCOPE_PROTOTYPE * @see org.springframework.web.context.WebApplicationContext#SCOPE_REQUEST * @see org.springframework.web.context.WebApplicationContext#SCOPE_SESSION */ String value() default ConfigurableBeanFactory.SCOPE_SINGLETON;
是否可能是未加入依赖:
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.0.6.RELEASE</version> </dependency>
题主检查下是否在web.xml中声明了:
<listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener>
如果想在测试中mock一个session scope倒是简单:
factory.registerScope("session", new SessionScope());
自己解决了。
给@Scope设置了属性proxyMode
@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
@Bean
//@Scope("session")
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public SubDomain subDomain(){
return new SubDomain();
}
}
大概是因为,被注入的bean的作用域是Singleton,而Singleton的作用域要比Session广。