java - spring @scope的问题
伊谢尔伦
伊谢尔伦 2017-04-17 16:21:17
[Java讨论组]

我想在用户请求的时候,获取二级域名,并注册,然后想到处都能使用。
于是,写了下面的代码,希望在每个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'

是不是我缺少配置了?

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

全部回复(2)
迷茫

自己解决了。
给@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广。

迷茫

没有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());
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号