2011-08-19 74 views
1

这可能很明显,但我很难理解为什么我们需要定义bean的类在两个地方....为什么需要在xml文件中和Spring中的getBean()方法中指定该类

从春天参考手册... ...

<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的类?

回答

1

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

2

您可以使用下面的方法:

context.getBean("petStore") 

然而,因为这将返回一个java.lang.Object中,你仍旧需要有一个转换:

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

然而,这如果你的“petStore”bean实际上不是一个PetStoreServiceImpl,并且为了避免强制转换(因为泛型的出现被认为有点脏),可能会导致问题,你可以使用上面的方法来推断它的类型检查你期望的bean是否属于正确的类,因此你已经拥有了:

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(); 
} 

然后你可以在应用程序上下文挂钩豆:

你也可以通过XML废除的配置和使用注释要连接你的bean:

@Autowired 
private PetStoreService petStoreService; 

只要你有

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

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

尽管如此,从铸造的getBean(返回值),我们只是移动类从构造函数到演员定义。 – zerayaqob

+0

不知道你的构造函数是什么意思,但是由于Java编译器不解析应用程序上下文xml,所以需要通过调用getBean()的结果告诉它需要什么类型的对象。 – beny23

相关问题