了解IOC容器 - beans.xml

时间:2017-12-13 13:12:49

标签: java spring ioc-container

beans.xml下面的语法

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="springQuizMaster" class="com.vaannila.SpringQuizMaster"></bean>
    <bean id="strutsQuizMaster" class="com.vaannila.StrutsQuizMaster"></bean>
    <bean id="quizMasterService1" class="com.vaannila.QuizMasterService1">
        <property name="quizMaster">
        <ref local="springQuizMaster"/>
        </property>
    </bean>
    <bean id="quizMasterService2" class="com.vaannila.QuizMasterService2">
        <property name="quizMaster">
        <ref local="springQuizMaster"/>
        </property>
    </bean>    
</beans>

告诉 Spring IOC容器

1)

<bean id="springQuizMaster" class="com.vaannila.SpringQuizMaster"></bean>
<bean id="strutsQuizMaster" class="com.vaannila.StrutsQuizMaster"></bean>

只有班级springQuizMaster&amp;的实例如果需要,将来需要实例化类strutsQuizMaster作为依赖项。

另一个优点是,beans.xml可以在运行时使用新的依赖项进行更新,无需重新启动我的Spring应用程序,只需添加更多依赖项,例如<bean id="xyzQuizMaster" class="com.vaannila.XYZQuizMaster"></bean>

2)

<bean id="quizMasterService1" class="com.vaannila.QuizMasterService1">
    <property name="quizMaster">
    <ref local="springQuizMaster"/>
    </property>
</bean>
<bean id="quizMasterService2" class="com.vaannila.QuizMasterService2">
    <property name="quizMaster">
    <ref local="springQuizMaster"/>
    </property>
</bean>

告诉IOC容器维护以下map个依赖项:

class `QuizMasterService1` => array(class `SpringQuizMaster`,)
class `QuizMasterService2` => array(class `SpringQuizMaster`,)

在运行时实例化QuizMasterService1之后,从java代码中, array 中给出的相应依赖项将立即由IOC容器实例化。< / p>

这是对IOC容器的正确理解吗?

0 个答案:

没有答案