您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
20-Spring相应API2(getBean通过接口类来获取)
发布时间:2024-12-20 20:29:56编辑:雪饮阅读()
-
之前我们获取bean的时候像是这样
UserService userService= (UserService) app.getBean("userService");
这是通过bean的id去获取的,那么除了通过bean的id去获取bean,还可以通过字节码来获取,例如通过类来获取。
UserService userService= app.getBean(UserService.class);
当前这样使用的前提是该接口类的实现只有一个时候,例如Spring Config中局部配置如:
<bean id="userService" class="com.service.impl.UserServiceImplement">
<constructor-arg name="userDao" ref="userDao"/>
</bean>
<bean id="userService2" class="com.service.impl.UserServiceImplement">
<constructor-arg name="userDao" ref="userDao"/>
</bean>
像是这两个的class都是com.service.impl.UserServiceImplement,而com.service.impl.UserServiceImplement又是UserService.class接口的实现,所以这样是会报错的,因为都是同一个接口,无法区分了。到底要获取哪一个呢?
关键字词:Spring,getBean,类,获取