现在采用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
这个时候就