Я пытаюсь понять конфигурацию пружины. Я прочитал обе статьи:Лучшая конфигурация для весны 3.2.3
- http://www.onjava.com/pub/a/onjava/2006/03/22/advanced-spring-configuration.html?page=1
- http://syntx.io/difference-between-loading-context-via-dispatcherservlet-and-contextloaderlistener/
Они предполагают, чтобы иметь 2 конфигурационные файлы: «Контекст приложения» и «контекст веб-приложения».
Если вы когда-либо пытались разработать веб-приложения с помощью рамки Spring MVC, вы знаете, что есть два файла конфигурации, которые должны быть использованы:
/WEB-INF/applicationContext.xml позволяет настройте свои компоненты, или , чтобы указать контекст вашего приложения. Это место, где вы определяете свои бизнес-логику, ресурсы и все остальные компоненты , которые не имеют прямого отношения к веб-уровню.
/WEB-INF/[servlet-name]-servlet.xml используется для настройки веб-уровня и просматривать арбитры, контроллеры, валидаторы, и все другие бобы, которые вам нужно в рамках MVC. [Имя сервлета] относится к имени сервлета диспетчера Spring, определенного в дескрипторе развертывания web.xml .
В соответствии с этим, я пишу web.xml следующим образом:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- Application Context -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml,
/WEB-INF/spring-security.xml</param-value>
</context-param>
<!-- Spring MVC -->
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>
org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Fin Spring Security -->
</web-app>
Это мой 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:mvc="http://www.springframework.org/schema/mvc" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd">
<!-- Look in tom cats context -->
<jee:jndi-lookup id="myDataSource" jndi-name="java:comp/env/jdbc/rhcimax"/>
<!-- Hibernate Session Factory -->
<bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="packagesToScan">
<array>
<value>com.blah.baseProject</value>
</array>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQLDialect
</value>
</property>
</bean>
<!-- Hibernate Transaction Manager -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
<!-- Activates annotation based transaction management -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
И это мой MVC-диспетчерская-сервлет. 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:mvc="http://www.springframework.org/schema/mvc" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<!-- Enable @Controller annotation support -->
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
<mvc:resources mapping="/resources/**" location="/resources/" />
<!-- Map simple view name such as "test" into /WEB-INF/views/test.jsp -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/view/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Scan classpath for annotations (eg: @Service, @Repository etc) -->
<context:component-scan base-package="com.blah.baseProject"/>
</beans>
Я хочу знать, является ли эта конфигурация почти cor Прямоугольник. Эта конфигурация работает, но я чувствую, что applicationContext.xml не называют, так как я получаю это исключение:
org.hibernate.HibernateException: No Session found for current thread
Мое намерение состоит в том, чтобы сохранить хорошие практики весной и узнать правильную конфигурацию.
«Это лучшая практика, чтобы сохранить четкое разделение между средним уровнем услуги, такими как бизнес-логикой компоненты и данными классы доступа (которые, как правило, определены в ApplicationContext) и веб- связанных компонентов, такие как контроллеров и разрешающих представлений (то есть , определенных в WebApplicationContext для сервлета диспетчера). "
Он очень благодарит! Я объявил компонент-сканирование только для контроллеров в конфигурации сервлета, как вы уже упоминали, и теперь все работает нормально !!. Я не получаю исключения :). Еще одно последнее: можете ли вы поделиться своим application-context.xml и application-context-db.xml? – kiduxa
Готово. См. Обновленный ответ – yname