Spring Bean为单例的正确理解

现在采用Spring进行开发的Java从业者越来越多,Spring也逐渐成为构建其他框架例如Spring Boot、Spring Cloud的基石,Spring Bean应该是大家用得最多的东西了,而且想用只需要用@Autowired注解引入即可,实在是太方便了,以前开发任何东西都要先new再使用。这正是Spring框架设计的初衷,就是你什么都不需要懂,Spring容器在系统启动的时候就帮你都创建好,你随用随取。Spring容器为我们创建的Bean都是单例Bean(原型Bean先放一边),这也极大的节省了创建和销毁对象产生的垃圾回收的开销。

真的是某个接口就生成一个Bean吗,能不能同一接口生成多个Bean呢?当然可以,相信很多同学就用过不同的实现类实现同一接口,但启动的时候会报下面的错:

Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'stuRpcService': Unsatisfied dependency expressed through field 'orderService'; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.example.intf.OrderService' available: expected single matching bean but found 2: orderService1,orderService2

这个时候就

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值