Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where are valid values defined for @Scope in web-aware and portal spring contexts?

The following allows the declaration of a singleton bean in Spring 3.0:

@Bean
@Scope(BeanDefinition.SCOPE_SINGLETON)
private void setBean1(Bean1 b1) {
    this.b1 = b1;
}

But, BeanDefinition does not define scopes values for request, session and global session. Where are these defined? Else, should I use @Scope("request"), @Scope("session") and @Scope("global session")?

like image 785
Jérôme Verstrynge Avatar asked Jul 01 '12 13:07

Jérôme Verstrynge


People also ask

Which of the following is valid only in a Web-Aware Spring ApplicationContext?

Session: Scopes a single bean definition to the lifecycle of an HTTP Session. But Only valid in the context of a web-aware Spring ApplicationContext. Global-Session: Scopes a single bean definition to the lifecycle of a global HTTP Session. It is also only valid in the context of a web-aware Spring ApplicationContext.

What is @scope annotation in Spring?

When used as a type-level annotation in conjunction with @Component , @Scope indicates the name of a scope to use for instances of the annotated type. When used as a method-level annotation in conjunction with @Bean , @Scope indicates the name of a scope to use for the instance returned from the method.

What is @scope in Spring boot?

A scope defines the runtime context within which the bean instance is available. In Spring, a bean can be associated with the following scopes: Singleton. Prototype. Request.

Which of the following are considered valid beans?

6. Which of the following are considered valid beans? Explanation: In Spring 1. x, singleton and prototype are the only two valid bean scopes, and they are specified by the singleton attribute (i.e., singleton=”true” or singleton=”false”), not the scope attribute.


3 Answers

BeanDefinition only has SCOPE_SINGLETON and SCOPE_PROTOTYPE.

The other scopes, being only applicable to web applications, are defined in org.springframework.web.context.WebApplicationContext.

A useful list of constants can be found in the javadoc for Constant Field values.

like image 95
Don Roby Avatar answered Sep 20 '22 14:09

Don Roby


You can use string literals if you want (though global session would be "globalSession").

Alternatively, you can use constants defined in WebApplicationContext.

like image 23
axtavt Avatar answered Sep 22 '22 14:09

axtavt


There is no single place, where all the scope names are defined, and not all scope names have constants:

  • singleton -> ConfigurableBeanFactory#SCOPE_SINGLETON
  • prototype -> ConfigurableBeanFactory#SCOPE_PROTOTYPE
  • request -> WebApplicationContext#SCOPE_REQUEST
  • session -> WebApplicationContext#SCOPE_SESSION
  • application -> WebApplicationContext#SCOPE_APPLICATION
  • websocket -> not defined (at lease I did not find)
like image 37
armansimonyan13 Avatar answered Sep 22 '22 14:09

armansimonyan13