Java Spring 会自动查找并解析带有 bean 声明的 xml 文件



我最近在玩一个复杂的Spring MVC应用程序。我将我的 servlet 调度程序设置为自动查找控制器类。

<!-- Scans for application @Components to deploy -->
<context:component-scan base-package="com.example."/>
<context:annotation-config/>
<context:spring-configured />
<tx:annotation-driven transaction-manager="transactionManager"/>

因此,据我了解,它会遍历所有罐子并尝试找到所有控制器。

有趣的是,在类路径上的一个 jar 中,我有以下文件 myFile.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-3.0.xsd">
<!-- This bean is the parent ApplicationContext for the WebApplicationContexts defined in the WARs. 
     The context files listed here should contain beans that are used by all WARs, for example Services and DAOs. -->
<bean id="grants-app.context" class="org.springframework.context.support.ClassPathXmlApplicationContext">
    <constructor-arg>
        <list>
            <value>/example/config.xml</value>
            <value>/example/app-config.xml</value>
        </list>
    </constructor-arg>
</bean>
</beans> 

不知何故,Spring 拿起这个文件并尝试制作这个文件中定义的 bean。我不理解这种行为 - 我只告诉 Spring 寻找控制器类。请问有人可以解释一下这里发生了什么吗?

你需要查看你的网络.xml。当您的每个 Web 应用程序都想要访问常见的源代码(如服务和 daos)时(在您的案例中,它们可能位于 EAR 的 jar 中),您可以在上下文参数中指定它,如以下示例所示:

    <!--  root application context -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:rootContextBeans.xml</param-value>
    </context-param>
    <!--  shared service layer - parent application context -->
    <context-param>
        <param-name>locatorFactorySelector</param-name>
        <param-value>classpath:myFile.xml</param-value>
    </context-param>
    <context-param>
        <param-name>parentContextKey</param-name>
        <param-value>servicelayer-context</param-value>
    </context-param>
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>

和我的文件.xml会像

    <beans>
      <bean id="servicelayer-context" class="org.springframework.context.support.ClassPathXmlApplicationContext">
        <constructor-arg>
          <list>
                <value>/example/config.xml</value>
                <value>/example/app-config.xml</value>
            </list>
        </constructor-arg>
      </bean>
    </beans>

正是web中的这个ContextLoaderListener/contextLoader(较旧的春季版本).xml它从myFile加载这些文件.xml

最新更新