为什么需要在xml文件和Spring中的getBean()方法中指定类

时间:2011-08-19 14:27:52

标签: spring

这可能是显而易见的,但我很难理解为什么我们需要在两个地方定义bean的类....

从春季参考手册...... ...

<bean id="petStore"
class="org.springframework.samples.jpetstore.services.PetStoreServiceImpl">
<property name="accountDao" ref="accountDao"/>
<property name="itemDao" ref="itemDao"/>
<!-- additional collaborators and configuration for this bean go here -->
</bean>

// retrieve configured instance
PetStoreServiceImpl service = context.getBean("petStore", PetStoreServiceImpl.class);

xml是否应该足以让容器知道petStore的类?

2 个答案:

答案 0 :(得分:2)

您可以使用以下方法:

context.getBean("petStore")

但是,因为这会返回一个java.lang.Object,你仍然需要一个强制转换:

PetStoreServiceImpl petstore = (PetStoreServiceImpl)context.getBean("petStore");

但是,如果您的“petStore”bean实际上不是PetStoreServiceImpl,并且为了避免强制转换(由于Generics的出现被认为有点脏),这可能会导致问题,您可以使用上面的方法来推断类型(让我们春天检查你期待的豆是否真的是正确的类,所以你得到了:

PetStoreServiceImpl service = context.getBean("petStore", PetStoreServiceImpl.class);

希望有所帮助。

编辑:

就个人而言,我会避免调用context.getBean()来查找方法,因为它违背了依赖注入的想法。实际上,使用petstore bean的组件应该有一个属性,然后可以使用正确的组件注入该属性。

private PetStoreService petStoreService;

// setter omitted for brevity

public void someotherMethod() {
    // no need for calling getBean()
    petStoreService.somePetstoreMethod();
}

然后你可以在应用程序上下文中连接bean:

           

您也可以通过XML取消配置并使用注释来连接您的bean:

@Autowired
private PetStoreService petStoreService;

只要你有

在spring上下文中,将自动注入在应用程序上下文中定义的“petStore”bean。如果你有多个类型为“PetStoreService”的bean,那么你需要添加一个限定符:

@Autowired
@Qualifier("petStore")
private PetStoreService petStoreService;

答案 1 :(得分:1)

不需要在getBean()方法中指定类。这只是一个安全问题。请注意,还有一个getBean()只使用 类,这样您就可以按类型查找bean而不需要知道名称。