问题
A request scoped bean in spring means that the container create a single bean instance per HTTP request.
Let say I have a RequestScopedBean bean :
@Component
public class RequestScopedBean {
@PostConstruct
void init() {
System.out.println("Init method called for each incoming HTTP Request");
}
}
public void doSomething() {}
Configuration :
@Configuration
public class MyBeansConfig {
@Bean
@Scope(value="request", proxyMode=TARGET_CLASS)
public RequestScopedBean requestScopedBean() {
return new requestScopedBean();
}
}
I'm using my RequestScopedBean inside a Singleton bean - and I'm expecting that the init() method is called for each incoming HTTP request. But it is not. The init() method is called only one time meaning the container create only one instance of my RequestScopedBean !!! Can someone explain to me: if the behavior i'm expecting is correct / or what's wrong with the configuration.
回答1:
You have done redundant configuration for your RequestScopedBean. In case of spring managed bean (like @Component), you need NOT define the same in a Configuration class with @Bean. You can just leave the class annotated with @Component and spring will scan it for you and instantiate it whenever required. And the scope of it can be provided at the class level. Like this:
@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");
}
Otherwise, you can define a @Bean method, wherein you instantiate ANY class (not necessarily a spring managed bean), set the required parameters and return the instance. The scope in this case can be provided at the method level. Like this:
@Configuration
public class MyBeansConfig {
@Bean
@Scope(value="request", proxyMode=ScopedProxyMode.TARGET_CLASS)
public RequestScopedBean requestScopedBean() {
//if needed set the required parameters
return new RequestScopedBean();
}
}
In your case, you have done both, which is not required and probably thats why its not behaving as expected. To solve your problem do any one of the following,
- Remove the @Component annotation in the RequestScopedBean class.
OR
- Add the @Scope annotation as shown above in the RequestScopedBean AND remove the @Bean method for RequestScopeBean from the Configuration class.
来源:https://stackoverflow.com/questions/39486763/instanciation-of-a-request-scoped-bean