作者:小猿聊编程
更多资料:https://www.techlearn.cn/
作用:@Scope用来配置 spring bean 的作用域,它标识 bean 的作用域是单实例还是多实例,该注解可以作用在类和方法上面,通过属性来控制作用域。
使用范围:类、方法。
参数:value
和scopeName
效果一样,用来指定bean作用域名称。
定义
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Scope {
@AliasFor("scopeName")
String value() default "";
@AliasFor("value")
String scopeName() default "";
ScopedProxyMode proxyMode() default ScopedProxyMode.DEFAULT;
}
属性介绍
value:
singleton -> 在spring IoC容器仅存在一个Bean实例,Bean以单例方式存在,bean作用域范围的默认值
prototype -> 表示该bean是多例的,即每次从容器中调用Bean时,都返回一个新的实例
request -> 每次HTTP请求都会创建一个新的Bean,一个bean对应一个实例
session -> 同一个HTTP Session共享一个Bean,不同Session使用不同的Bean
proxyMode:
DEFAULT 不使用代理。(默认)
NO -> 不使用代理,等价于DEFAULT。
INTERFACES -> 使用基于接口的代理(jdk dynamic proxy)
1、与和@Compontent一起使用在类上
下面我们定义一个bean,作用域是单例
@Component
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public class Service {
}
2、和@Bean一起标注在方法上
@Bean标注在方法上,可以通过这个方法来向spring容器中注册一个bean,在此方法上加上@Scope可以指定这个bean的作用域,如:
public class Service{
}
@Configurable
public class ServiceConfig {
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) //@1
public Service service() {
return new Service();
}
}
public class injectTest {
@Test
public void test(){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(ServiceConfig.class);
Object service = applicationContext.getBean("service");
Object service2 = applicationContext.getBean("service");
System.out.println(service);
System.out.println(service2);
}
}
运行结果
com.example.demo.service.Service@606e4010
com.example.demo.service.Service@8458f04
以上运行结果,表明两次从spring容器中获取的bean不是同一个
Spring 只帮我们管理单例模式 Bean 的完整生命周期,对于 prototype 的 bean ,Spring 在创建好交给使用者之后则不会再管理后续的生命周期。