Scope describes how a spring container can create instances of a new bean, in the following ways:
1.Singleton: There is only one instance of the bean in a spring container, this is the default configuration of spring, and the whole container shares an instance;
2.Prototype: Each time a new instance of a bean is called;
3.request:web project, create a new bean instance for each HTTP Request;
4.session:web project, create a new bean instance for each HTTP Session;
5.GlobalSession: This is only useful in portal applications, creating a new bean instance for each global HTTP session;
In addition, there is one scope in spring batch that uses @stepscope, which is described in the batch section.
@Service@Scope("prototype")//如果不声明就相当于采用默认值@Scope("singleton")public class DemoPrototypeService{}
Example
1> writing a singleton bean
package com.wisely.highlight_spring4.ch2.scope;import org.springframework.stereotype.Service;@Service //默认为Singleton,相当于@Scope("singleton")public class DemoSingletonService {}
2> writing a prototype bean
package com.wisely.highlight_spring4.ch2.scope;import org.springframework.context.annotation.Scope;import org.springframework.stereotype.Service;@Service@Scope("prototype")//声明Scope为Prototypepublic class DemoPrototypeService {}
3> Configuration class
package com.wisely.highlight_spring4.ch2.scope;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;@Configuration@ComponentScan("com.wisely.highlight_spring4.ch2.scope")public class ScopeConfig {}
4> run
package com.wisely.highlight_spring4.ch2.scope;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Main { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScopeConfig.class); DemoSingletonService s1 = context.getBean(DemoSingletonService.class); DemoSingletonService s2 = context.getBean(DemoSingletonService.class); DemoPrototypeService p1 = context.getBean(DemoPrototypeService.class); DemoPrototypeService p2 = context.getBean(DemoPrototypeService.class); System.out.println("s1与s2是否相等:"+s1.equals(s2)); System.out.println("p1与p2是否相等:"+p1.equals(p2)); context.close(); }}
Spring Boot Tutorial 4--@Scope annotations