博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring或者Springboot实现多例
阅读量:3764 次
发布时间:2019-05-22

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

概述

通过Spring管理的类,默认是单例模式,但是如果有的类需要使用独立的属性,则需要配置为多例模式的. 但是多例模式不仅仅只是加一个声明,使用@Autowired进行注入,可能并不会是你想要的结果.因为多例模式的类是需要单独调用的.
不搞清楚原理直接测试:
需要多例的类上加上注解@Scope(“prototype”)

@Component@Scope("prototype")public class ExampleService{	public void test(){		System.out.println("test,current bean is" + this);	}	}

引用直接使用@Autowired

@Controllerpublic class ExampleService{	@Autowired	private ExampleService exampleService;		@RequestMapping("test")	public void test(){		exampleService.test();	}	}

结果: 每个request过来的时候,exampleService实例均为同一个实例.

解决办法:

第一种:不使用@Autowired

@Controllerpublic class ExampleService{	@Autowired	private org.springframework.beans.factory.BeanFactory beanFactory;		@RequestMapping("test")	public void test(){		ExampleService exampleService = beanFactory.getBean(ExampleService.class);		exampleService.test();	}}

第二种:使用bean工厂

@Autowired private ApplicationContext context; @Bean    public WebSocketHandler websocketBHandler() {        PerConnectionWebSocketHandler perConnectionHandler = new PerConnectionWebSocketHandler(WebSocketBHandler.class);        perConnectionHandler.setBeanFactory(context.getAutowireCapableBeanFactory());        //设置bean工厂,否则bean工厂WebSocketBHandler将不会自动连接        return perConnectionHandler;    }

然后使用ApplicationContext进行代理bean工厂

注入@Autowiredprivate ApplicationContext context;使用this.Bservice = context.getBean(BService.class, this);

官方文档说明

4.5.3 Singleton beans with prototype-bean dependencies When you use singleton-scoped beans with dependencies on prototype beans, be aware that dependencies are resolved at instantiation time. Thus if you dependency-inject a prototype-scoped bean into a singleton-scoped bean, a new prototype bean is instantiated and then dependency-injected into the singleton bean. The prototype instance is the sole instance that is ever supplied to the singleton-scoped bean. However, suppose you want the singleton-scoped bean to acquire a new instance of the prototype-scoped bean repeatedly at runtime. You cannot dependency-inject a prototype-scoped bean into your singleton bean, because that injection occurs only once, when the Spring container is instantiating the singleton bean and resolving and injecting its dependencies. If you need a new instance of a prototype bean at runtime more than once, see Section 4.4.6, “Method injection”
《参考:

转载地址:http://poipn.baihongyu.com/

你可能感兴趣的文章
Spring 事务管理
查看>>
spring与mybatis的整合
查看>>
json数据交换和RESTful支持
查看>>
spring中的拦截器
查看>>
文件上传和下载
查看>>
Oracle指令,软件架构,
查看>>
oracle5:oracle的图形界面操作,分页查询,练习
查看>>
密码学基础之对称密码体制和公钥密码体制
查看>>
Spark Streaming进阶
查看>>
C++顺序表经典算法
查看>>
网络安全与管理知识点总结
查看>>
YARN的概述
查看>>
企业级ansible(一)-----ansible的基础知识了解
查看>>
有关IP及IP设定方式 ,改造虚拟机做路由
查看>>
路由器的搭建虚拟机上网及DHCP服务、dns解析
查看>>
linux系统的定时、延迟任务管理
查看>>
linux系统的磁盘管理方式
查看>>
管理lvm(Logical Volume Manager)
查看>>
yum源的配置及第三方软件仓库的管理、yum命令、rpm命令的使用
查看>>
linux系统的selinux管理
查看>>