博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring注解Scope
阅读量:6856 次
发布时间:2019-06-26

本文共 1652 字,大约阅读时间需要 5 分钟。

hot3.png

@Scope注解的范围

  1. Singleton:一个Spring容器只有一个Bean实例,也是默认配置
  2. Prototype:每次调用新建一个Bean实例
  3. Request:web项目中,每一个http request新建一个Bean实例
  4. Session:web项目中,每一个http session新建一个Bean实例
  5. GlobalSession:portal应用中使用

单例service类

import org.springframework.stereotype.Service;/** * @author Kevin * @description * @date 2016/6/30 */@Service// 默认为singleto 相当于@Scope("singleton")public class DemoSingletonService {}

Prototype service类

import org.springframework.context.annotation.Scope;import org.springframework.stereotype.Service;/** * @author Kevin * @description * @date 2016/6/30 */@Service@Scope("prototype")public class DemoPrototypeService {}

配置类

import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;/** * @author Kevin * @description * @date 2016/6/30 */@Configuration// 扫描所在包@ComponentScan("ch02.scope")public class Config {}

运行

import org.springframework.context.annotation.AnnotationConfigApplicationContext;/** * @author Kevin * @description * @date 2016/6/30 */public class Main {    public static void main(String[] args) {        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.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 == s2));        System.out.println("p1 == p2 : " + (p1 == p2));    }}

结果

091021_2AHf_1421353.png

转载于:https://my.oschina.net/kevinair/blog/703026

你可能感兴趣的文章
iscsi集群搭建
查看>>
Flutter Web - 目标全平台开发的Flutter再下一城!
查看>>
Nginx代理Tomcat
查看>>
Apache与Tomcat的区别
查看>>
mysql—Access denied for user 'root'@'localhost' (using password:NO)
查看>>
hibernate 懒加载异常
查看>>
python3的zip函数
查看>>
《Git权威指南》读书笔记 第四章 git初始化
查看>>
《Head first HTML与CSS 第二版》读书笔记 第九章 盒模型
查看>>
《Python面向对象……》之目录
查看>>
集群入门简析及LB下LVS详解
查看>>
Linux与GPT
查看>>
管理或技术
查看>>
分配到弱属性;对象将在赋值之后释放
查看>>
java作用域public ,private ,protected 及不写时的区别
查看>>
until循环语句
查看>>
Android桌面悬浮窗进阶,QQ手机管家小火箭效果实现
查看>>
提高用户体验方式:饥饿营销
查看>>
Java8中的LocalDateTime工具类
查看>>
Exchange 2013 PowerShell创建自定义对象
查看>>