2016-09-14 82 views
0

Spring中的請求作用域bean意味着容器爲每個HTTP請求創建一個bean實例。請求作用域bean的實例化

讓說我有一個RequestScopedBean豆:

@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(); 
    }   
} 

我用我的RequestScopedBean一個辛格爾頓豆裏面 - 和我期待的是,爲每個傳入的HTTP請求調用init()方法。但事實並非如此。 init()方法只被調用一次,這意味着容器只創建一個我的實例RequestScopedBean !!! 有人可以向我解釋:如果我期望的行爲是正確的/或配置有什麼問題。

回答

1

您已完成RequestScopedBean的冗餘配置。 在彈簧託管bean(如@Component)的情況下,您不需要在具有@Bean的Configuration類中定義相同的值。您可以將類註釋爲@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"); 

}

否則,您可以定義一個@Bean方法,其中實例化任何類(不一定是春季管理的bean),設置所需的參數和返回的實例。這種情況下的範圍可以在方法級別提供。就像這樣:

@Configuration 
public class MyBeansConfig { 
    @Bean 
    @Scope(value="request", proxyMode=ScopedProxyMode.TARGET_CLASS) 
    public RequestScopedBean requestScopedBean() { 
    //if needed set the required parameters 
    return new RequestScopedBean(); 
    }   
} 

在你的情況,你做了兩個,這不是必須的,也許這就是預期爲什麼它不表現。要解決您的問題,請執行以下任一操作:

  1. 刪除RequestScopedBean類中的@Component註釋。

OR

  • 添加如RequestScopedBean上面所示@Scope註解,並從配置類移除RequestScopeBean的@Bean方法。
  • 相關問題