2012-02-10 3 views
4

У меня было два вопроса,Web-приложений и менеджер транзакций установки

В приложении Spring MVC, что цель иметь ContextLoaderListener?

Ниже приведены мои записи в web.xml, Все MVC бобы определены в сервлет-context.xml Все базы данных и управления транзакциями на основе аннотаций определяется в applicationContext.xml и я использую контейнер удалось транзакцию JBoss

Менеджер trasaction отлично работает, если я передаю applicationContext.xml, как указано ниже, как DispatcherServlet. Но я думал, что нам нужно передать только контекстную информацию Spring MVC в DispatcherServlet.

Если я удалю applicationContext.xml, менеджер транзакций перестает работать? Я смущен, что лучший способ управления файлами контекста?

web.xml

<listener> 
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
</listener> 

<context-param> 
    <param-name>contextConfigLocation</param-name> 
    <param-value>  
     /WEB-INF/config/applicationContext.xml 
     /WEB-INF/config/spring-mail.xml 
    </param-value> 
</context-param> 
<context-param> 
    <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name> 
    <param-value>messages</param-value> 
</context-param> 


<servlet> 
    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name> 
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
    <init-param> 
     <param-name>contextConfigLocation</param-name> 
     <param-value> 
      /WEB-INF/config/servlet-context.xml 
      ***/WEB-INF/config/applicationContext.xml*** 
     </param-value> 
    </init-param> 
    <load-on-startup>1</load-on-startup> 
</servlet> 

applicationContext.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" 
    xmlns:jee="http://www.springframework.org/schema/jee" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
      http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd 
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd 
      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> 

<!-- registers all of Spring's standard post-processors for annotation-based configuration --> 
<context:annotation-config /> 

<jee:jndi-lookup id="dataSource" jndi-name="java:OracleDS"/> 


<tx:annotation-driven/> 
<tx:jta-transaction-manager/> 

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 
    <property name="dataSource" ref="dataSource"/> 
    <property name="configLocation" 
       value="classpath:com/common/model/config/sqlmapconfig.xml"/> 
</bean> 

<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> 
    <constructor-arg ref="sqlSessionFactory"/> 
</bean> 

сервлет-context.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" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:mvc="http://www.springframework.org/schema/mvc" 
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 

<!-- Scans the classpath of this application for @Components to deploy as beans --> 
<context:component-scan base-package="com.xxxx"/> 

<!-- Configures the @Controller programming model --> 
<mvc:annotation-driven/> 

<!-- Configures Handler Interceptors --> 
<mvc:interceptors> 
    <!-- Changes the locale when a 'locale' request parameter is sent; e.g. /?locale=de --> 
    <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/> 
    <!--Register Request/Response Interceptor--> 
    <bean class="com.xxx.common.auditor.RequestInterceptor"/> 
    <!-- <bean class="com.xxx.common.interceptor.UserAuthenticationInterceptor"/>--> 
</mvc:interceptors> 

<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver"/> 

<!-- Application Message Bundle --> 
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> 
    <property name="basename" value="/WEB-INF/messages/messages"/> 
    <property name="cacheSeconds" value="0"/> 
</bean> 


<!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory --> 
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> 
    <property name="prefix" value="/WEB-INF/views/"/> 
    <property name="suffix" value=".jsp"/> 
</bean> 

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
    <property name="location"> 
     <value>/WEB-INF/xxxx.properties</value> 
    </property> 
</bean> 

Спасибо Вам помочь! Я знаю его цитату долго, но хотел, чтобы я понял себя лучше.

ответ

13

Как поясняется в the documentation, каждый сервлет диспетчера имеет свой собственный контекст приложения, в котором вы обычно определяете контроллеры, просматриваете разрешители и т. Д. И который наследует (и может переопределять beans) из контекста корневого приложения, который обычно содержит определения источника данных, службы среднего уровня и т. д.

ContextLoaderListener, как объясняет its documentation, используется для запуска и закрытия контекста корневого приложения Spring (из которого сервлет контексты наследуют).

Это также полезно, если вы хотите использовать Spring для своего среднего уровня, но вы не хотите использовать Spring MVC в качестве уровня презентации. В этом случае вы определяете контекст корневого приложения, используя ContextLoaderListener.

+0

на самом деле ничего не говорит о ссылках на весеннюю документацию, и, более того, о том, что я уже говорю, что я отделяю контекст Интернета и приложения –

+6

Ваш первый вопрос: в чем цель ContextLoaderListener. Ответ: запуск и закрытие корневого контекста приложения. Ваш второй вопрос: я смущен, что лучший способ управления файлами контекста. Ответ: услуги среднего уровня должны быть в корневом контексте, загружаемом ContextLoaderListener. Специальные компоненты Spring MVC должны быть определены в контексте диспетчерского сервлета, который наследуется от корневого. У вас есть два файла XML, но один контекст. У вас должен быть корневой контекст и контекст с областью сервлетов. –

+0

спасибо! ОК, у меня есть слушателю корневой контекст <контекст-парам> contextConfigLocation /WEB-INF/config/applicationContext.xml /WEB-INF/config/spring-mail.xml Не инициализирует ли он корневой контекст? И не будет ли сервлет диспетчера инициализировать веб-контекст? Кроме того, почему диспетчер транзакций перестает работать, если я не включаю информацию о контексте приложения в диспетчерский сервлет? –

Смежные вопросы