Spring 请求作用域bean的实例

Spring 请求作用域bean的实例,spring,requestscope,Spring,Requestscope,spring中的请求范围bean意味着容器为每个HTTP请求创建一个bean实例 假设我有一个RequestScopedBean bean: @Component public class RequestScopedBean { @PostConstruct void init() { System.out.println("Init method called for each incoming HTTP Request"); } } public void doSom

spring中的请求范围bean意味着容器为每个HTTP请求创建一个bean实例

假设我有一个RequestScopedBean bean:

@Component
public class RequestScopedBean {
  @PostConstruct
  void init() {
     System.out.println("Init method called for each incoming HTTP Request");
  }
}

public void doSomething() {}
配置:

@Configuration
public class MyBeansConfig {
  @Bean
  @Scope(value="request", proxyMode=TARGET_CLASS)
  public RequestScopedBean requestScopedBean() {
     return new requestScopedBean();
  }         
}
我在一个单例bean中使用我的RequestScopedBean——我希望为每个传入的HTTP请求调用init()方法。但事实并非如此。 init()方法只被调用一次,这意味着容器只创建我的RequestScopedBean的一个实例!!!
有人能给我解释一下:如果我期望的行为是正确的/或者配置有什么问题

您已经为RequestScopedBean进行了冗余配置。 对于spring管理的bean(比如@Component),您不需要在配置类中使用@bean定义相同的组件。您只需使用@Component注释该类,spring将为您扫描它,并在需要时实例化它。它的范围可以在班级级别提供。像这样:

@Component
@Scope(value="request", proxyMode=ScopedProxyMode.TARGET_CLASS)
public class RequestScopedBean {
 @PostConstruct
 void init() {
  System.out.println("Init method called for each incoming HTTP Request");
@Configuration
public class MyBeansConfig {
  @Bean
  @Scope(value="request", proxyMode=ScopedProxyMode.TARGET_CLASS)
  public RequestScopedBean requestScopedBean() {
    //if needed set the required parameters
     return new RequestScopedBean();
  }         
}
}

否则,您可以定义@Bean方法,在其中实例化任何类(不一定是spring管理的Bean),设置所需参数并返回实例。本例中的范围可以在方法级别提供。像这样:

@Component
@Scope(value="request", proxyMode=ScopedProxyMode.TARGET_CLASS)
public class RequestScopedBean {
 @PostConstruct
 void init() {
  System.out.println("Init method called for each incoming HTTP Request");
@Configuration
public class MyBeansConfig {
  @Bean
  @Scope(value="request", proxyMode=ScopedProxyMode.TARGET_CLASS)
  public RequestScopedBean requestScopedBean() {
    //if needed set the required parameters
     return new RequestScopedBean();
  }         
}
在您的情况下,您已经完成了这两项工作,这不是必需的,这可能就是为什么它的行为不符合预期的原因。要解决您的问题,请执行以下任一操作:

  • 删除RequestScopedBean类中的@Component注释
  • 在RequestScopedBean中添加如上所示的@Scope注释,并从配置类中删除RequestScopeBean的@Bean方法