我们正在开发Spring MVC项目。我们希望在部署EAR时初始化所有bean。以下是我们的web.xml文件:
<servlet>
<servlet-name>Spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Spring</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/Spring-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
以下是我们的Spring配置文件:
<context:component-scan base-package="com"></context:component-scan>
<context:annotation-config></context:annotation-config>
<mvc:annotation-driven></mvc:annotation-driven>
<!-- Switch on the Caching -->
<cache:annotation-driven />
<!-- Do the component scan path -->
<!-- <context:component-scan base-package="caching" /> -->
<bean id="ehcache"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
p:configLocation="WEB-INF/ehcache.xml" p:shared="true" /> <!-- Why changed to true? https://stackoverflow.com/a/16370326 -->
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
p:cacheManager-ref="ehcache" />
<!-- creating datasource -->
<bean id="dataSourceForFilters"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.mariadb.jdbc.Driver" />
<property name="url" value="jdbc:mariadb://ip:3306/demo" />
<property name="username" value="remote" />
<property name="password" value="password" />
</bean>
<bean id="dataSourceForData" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:/misoracle"></property>
</bean>
<!-- creating jdbctemplate and injecting datasource into it -->
<bean id="jdbcTemplateForFilters" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSourceForFilters"></property>
</bean>
<bean id="jdbcTemplateForData" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSourceForData"></property>
</bean>
<!-- end -->
<bean id="applicationContextProvider" class="com.providers.ApplicationContextProvider"></bean>
我们正在使用组件注释(@ Controller,@ Service,@ Repository)来定义bean。
在将EAR部署到服务器时,Beans根据我们的要求正在初始化。
当我们使用像'IP:port / context-root / rest'这样的URL模式访问应用程序时,Spring bean会再次初始化。
为什么豆子会再次初始化,有人可以帮忙吗?
答案 0 :(得分:1)
您的web.xml映射应如下所示:
<servlet>
<servlet-name>Spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Spring</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/Spring-servlet.xml</param-value>
</context-param>