java - spring @scope的问题

 鸟的蛋蛋 发布于 2022-10-31 20:16

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

是不是我缺少配置了?

2 个回答
  • 没有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());
    2022-11-12 01:50 回答
  • 自己解决了。
    给@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广。

    2022-11-12 01:50 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有