I read this "It is a best practice to keep a clear separation between middle-tier services such as business logic components and data access classes (that are typically defined in the ApplicationContext) and web- related components such as controllers and view resolvers (that are defined in the WebApplicationContext per Dispatcher Servlet)."
And decide configure my application like that 4 separate xml file
applicationContext.xml
<context:component-scan base-package="appname">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
dao.xml
<!-- MySQL JDBC Data Source-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://#{mysqlDbCredentials.hostname}:#{mysqlDbCredentials.port}/#{mysqlDbCredentials.name}"/>
<property name="username" value="#{mysqlDbCredentials.username}"/>
<property name="password" value="#{mysqlDbCredentials.password}"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="JpaPersistenceUnit" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect"/>
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.showSql">true</prop>
</props>
</property>
</bean>
<bean class="org.springframework.orm.jpa.JpaTransactionManager"
id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
and mvc-dispatcher-servlet.xml
<mvc:annotation-driven />
<context:component-scan base-package="appname" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
web.xml(load spring context)
<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/spring/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>/spring/*</url-pattern>
</servlet-mapping>
<!-- Load spring beans definition files -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/applicationContext.xml
/WEB-INF/spring/security.xml
/WEB-INF/spring/dao.xml
</param-value>
</context-param>
But I'm absolutly confused.
1)I don't understand how many context in this case I get.
2)I want easy replace tx mode on aspectj (which work just in ome context as I know). But when I replace I get error with transation.
Main problem that I want to have universal variant for both type of transaction
Here I add mode="aspectj" and I have annotation like #Service, #Resourse, on concrete classes
<tx:annotation-driven transaction-manager="transactionManager" mode="aspectj" proxy-target-class="true"/>
All seems should work but I get next exception on flush
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.persistence.TransactionRequiredException: no transaction is in progress
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:948)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:575)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1239)
at [internal classes]
at org.apache.logging.log4j.core.web.Log4jServletFilter.doFilter(Log4jServletFilter.java:66)
at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:194)
at [internal classes]
Caused by: javax.persistence.TransactionRequiredException: no transaction is in progress
at org.hibernate.ejb.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:993)
at sun.reflect.NativeMethodAccessorImpl.invoke0(NativeMethodAccessorImpl.java:-2)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
Please, help me uderstand better
convention is you have one root context, normally applicationContext.xml. Then different servlet contexts (for different modules/functionality)... myapp-servlet.xml.
The servlet context can see everything in root context, but not the other way. Controllers and webby stuff(static resources) go in servlet context, everything else (eg service, and security) go in root context.
You can import different files as you please. But define those two contexts in your web.xml (or Java conf equivalent).
I still do it the old fashioned xml way, you don't have to use java conf.
Whats your actual error ?
Related
Well, very likely there isn't any mystery but I am just not smart enough to figure out what my problem is. However usually it is the mystery after all!
Sorry for the introduction, my problem is that the prototype scope doesn't seem to work for me. I have created a REST service with a Spring Integration flow (there is a http inbound gateway in the front of the flow). The scopes of most of the beans are prototype. I tested the flow by calling it ten times with threads. Also I logged the bean references (just print the 'this' in the object being called) and I saw the same reference ten times!
e.g. org.protneut.server.common.utils.XmlToMapConverter#755d7bc2
To my knowledge it means that no new instance is being created for the XmlToMapConverter but using the same instance ten times. Am I right?
Very likely I configured the Spring incorrectly but I just cannot find out what I missed.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/SpringIntegration-servlet.xml</param-value>
</context-param>
<servlet>
<servlet-name>SpringIntegration</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>SpringIntegration</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
SpringIntegration-servlet.xml
<beans ...>
<mvc:annotation-driven/>
<context:component-scan base-package="org.protneut.server.controller, org.protneut.server.common.persistence.service" />
<jpa:repositories base-package="org.protneut.server.common.persistence.repository"/>
<!-- ********************* importing the mysql config ********************* -->
<import resource="/mysql-config-context.xml"/>
<!-- ********************* importing the message flow ********************* -->
<import resource="classpath:META-INF/spring/integration/processing_req_wokflow.xml"/>
<tx:annotation-driven />
<!-- ************************************************************************* -->
<!-- ******************************** for JPA ******************************** -->
<!-- ************************************************************************* -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="org.protneut.server.common.persistence.model" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect"/>
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<!-- ********************* the used property files ********************* -->
<context:property-placeholder location="classpath:protneut-server-config.properties"/>
<!--
****************************************************************************************
********************** Beans used in the Spring Integration flow **********************
****************************************************************************************
-->
<!-- it has to be prototype, it cannot be request as it is in an async call so it is not in the request! -->
<bean id="logManager" class="org.protneut.server.log.LogManager" scope="prototype"></bean>
<bean id="convertRestToWorkflowBean" class="org.protneut.server.rest.ConvertRestMessageToWorkflowBean" scope="prototype"/>
<bean id="xmlToMapConverter" class="org.protneut.server.common.utils.XmlToMapConverter" scope="prototype"/>
<bean id="serviceStorageManager" class="org.protneut.server.cache.ServiceStorageManager" scope="singleton">
<property name="cacheBeanDAO" ref="cacheBeanDAO"/>
</bean>
<bean id="serviceCall" class="org.protneut.server.call.ServiceCall" scope="prototype">
<property name="httpClient" ref="httpClient"/>
</bean>
<bean id="xmlResponseExtractor" class="org.protneut.server.extract.XmlResponseExtractor" scope="prototype">
<property name="xmlToMapConverter" ref="xmlToMapConverter"/>
</bean>
...
</beans>
flow configuration
<?xml version="1.0" encoding="UTF-8"?>
<beans ..>
<task:executor id="async_executor" pool-size="50" />
<!-- ***************************************************************************************************** -->
<!-- ************************************* WORKFLOW STARTING ********************************************* -->
<!-- ***************************************************************************************************** -->
<int-http:inbound-gateway id="receivingRest-inboundGateway"
supported-methods="POST" path="/service/get"
request-payload-type="java.lang.String" reply-timeout="10000"
request-channel="arrivedRestReq_channel" auto-startup="true"
error-channel="error_channel" reply-channel="restResponse-channel" >
</int-http:inbound-gateway>
<int:channel id="arrivedRestReq_channel" scope="prototype"></int:channel>
<int:json-to-object-transformer type="java.util.Map"
input-channel="arrivedRestReq_channel"
output-channel="fromConvertToActivator-channel"
id="convertJsonToMap_">
</int:json-to-object-transformer>
<int:channel id="fromConvertToActivator-channel"></int:channel>
<int:service-activator
input-channel="fromConvertToActivator-channel"
output-channel="toCallChain-channel"
id="convertRestToWorkflowBean-serviceActivator"
ref="convertRestToWorkflowBean" method="convert">
</int:service-activator>
<int:channel id="toCallChain-channel"></int:channel>
<int:chain input-channel="toCallChain-channel" id="call_chain">
<int:service-activator
id="serviceStorageManager-serviceActivator"
ref="serviceStorageManager" method="getServiceInfo">
</int:service-activator>
<int:service-activator id="serviceRequestCreator-serviceActivator" ref="serviceRequestCreator" method="create"/>
<int:service-activator id="call-serviceActivator"
ref="serviceCall" method="call">
</int:service-activator>
<int:router expression="payload.extractType.name()"
id="responseExtractor-router">
<int:mapping value="XPATH" channel="xmlResponse-channel"/>
<int:mapping value="JSONPATH" channel="jsonResponse-channel"/>
</int:router>
</int:chain>
...
<int:service-activator id="xmlResponseExtractor-serviceActivator"
ref="xmlResponseExtractor" method="extract" input-channel="xmlResponse-channel" output-channel="toRestResponseCreator_chain"></int:service-activator>
</beans>
So I defined the scope of XmlToMapConverter is prototype but still I can't have new object at a new request. The situation is the same for convertRestToWorkflowBean which is the first service call in the flow (service-activator).
Could you please explain to me where the problem is?
Thanks, V.
I don't see xmlToMapConverter usage, but I see this:
<int:service-activator
input-channel="fromConvertToActivator-channel"
output-channel="toCallChain-channel"
id="convertRestToWorkflowBean-serviceActivator"
ref="convertRestToWorkflowBean" method="convert">
where you use this:
<bean id="convertRestToWorkflowBean" class="org.protneut.server.rest.ConvertRestMessageToWorkflowBean" scope="prototype"/>
The issue you are facing is called scope impendance. That's because <int:service-activator> populates several singleton beans, hence the reference to your prototype becomes as singleton, too.
One way to overcome that to use SpEL from there:
<int:service-activator
input-channel="fromConvertToActivator-channel"
output-channel="toCallChain-channel"
id="convertRestToWorkflowBean-serviceActivator"
expression="#convertRestToWorkflowBean.convert(payload)"/>
In this case your convertRestToWorkflowBean is retrieved from the BeanFactory on each call.
Another trick to go ahead looks like:
<bean id="convertRestToWorkflowBean" class="org.protneut.server.rest.ConvertRestMessageToWorkflowBean" scope="prototype">
<aop:scoped-proxy/>
</bean>
In this case your bean will be wrapped to the ScopedProxyFactoryBean and all invocation will be delegated to your prototype on demand.
Prototype scoped beans will be created every time you call ApplicationContext.getBean(...)
You've included the bean definition but haven't shown how other services reference it. My guess is it's injected into a singleton service once during initialization hence there's only one. Perhaps you need to call ApplicationContext.getBean() each time to get a new instance.
There are other solutions involving dynamic proxies that ultimately invoke getBean(), I'm on my mobile at the moment so too hard to find a link for you.
I've got a strange problem which I think is Spring related. I'm developing a Maven multi module application structured as follow:
DataModule (includes generale Hibernate entities and daos)
ServiceModule (includes specific Hibernate entities and daos) - depends on DataModule
Web (gwt web module) - depends on ServiceModule
In DataModule I've a classic Spring-Hibernate xml configuration, consisting of (relevant code):
ApplicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans ..>
<!-- Auto scan the components -->
<context:annotation-config />
<context:component-scan base-package="com.x.dataModule" >
<context:include-filter type="regex"
expression="com.x.dataModule.dao.*" />
</context:component-scan>
<!-- Import resources -->
<import resource="applicationContext-hibernate.xml" />
<import resource="applicationContext-dataSource.xml" />
</beans>
applicationContext-hibernate.xml
<beans ..>
<bean id="defaultLobHandler" class="org.springframework.jdbc.support.lob.DefaultLobHandler" />
<!-- Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean ">
<property name="packagesToScan" value="com.x.dataModel.model.**.*"></property>
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
<property name="lobHandler" ref="defaultLobHandler" />
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.query.substitutions">true 1, false 0</prop>
<prop key="hibernate.connection.useUnicode">true</prop>
<prop key="hibernate.connection.charSet">UTF8</prop>
</props>
</property>
</bean>
<!-- Transaction Manager -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
</beans>
Hibernate.cfg is actually empty, since I aim to avoid explicit mapping due the use of packagesToScan property. applicationContext-dataSource is not relevant since it contains ds configuration.
The ServiceModule relies on the previous module.
applicationContext.xml
<beans ...>
<!-- Auto scan the components -->
<context:include-filter type="regex"
expression="com.x.serviceModule.dao.*" />
<context:include-filter type="regex"
expression="com.x.serviceModule.manager.*" />
<!-- Import resources -->
<context:property-override location="classpath:override.properties"/>
<import resource="classpath*:/applicationContext-hibernate.xml" />
<import resource="classpath*:/applicationContext-dataSource.xml" />
</beans>
The file override.properties contains the following entry, to modify the definition of packagesToScan
sessionFactory.packagesToScan=com.x.*.model.**.*
At this point everything works just fine. The serviceManagers (singletons) are loaded from the factory as
ApplicationContext appContext = new ClassPathXmlApplicationContext(
"applicationContext.xml").getBean(..);
And everything is behaving as expected.
Last part, the Web Module. If I import the ServiceModule and test it as a Java application, again everything is fine. However, if I start the module as a web application, it fails complaining that it's not able to load entities/daos defined in the DataModule.
Relevant files in Web Module:
WEB-INF/spring
applicationContext.xml: nothing here other than the import of applicationContext-security.xml (residing in the same directory)
web.xml
<!-- Spring context -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
WEB-INF/spring/applicationContext.xml
</param-value>
</context-param>
<!-- Creates the Spring Container -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
The only way to avoid the problem is to declare explicitly the entities mapping and daos definition in the DataModule xml files.
My question: is there a way to avoid such declarations, and rely entirely on the component/package scan also in Web Module?
I'm not really sure but looks like that somehow the spring web context is conflicting with my other spring context. Otherwise, I don't understand why everything is fine as Java application, but fails as web.
Also (not sure if relevant) it seems that the Session Factory bean is istantiated twice during the process (shouldn't it be a singleton?).
Spring version is 3.1.1 Release, Hibernate 3.6.0 Final (4.0.1 for commons-annotations). Tomcat 7 for deploy.
I didn't provide the Java code of entities/daos/managers since I don't think it's relevant for the question; however, I can provide it if it's of any help. Thanks a lot
I have multiple config files in my web.xml:
<!-- Spring MVC ========================================================================== -->
<servlet>
<servlet-name>MoJV_SpringMVCDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/mo/MoJV/config/MoJVConfig.xml
/mo/App/config/AppConfig.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
In MoJVConfig.xml i have
<bean id="messageSource" class="mo.MoJV.src.I18N">
<property name="defaultEncoding" value="utf-8" />
<property name="fallbackToSystemLocale" value="true" />
<property name="cacheSeconds" value="3" />
<property name="files" value="/mo/MoJV/i18n/" />
</bean>
In AppConfig.xml I would like to only call setWorkingDirectory on the same messagesource. I have tried with
<bean id='messageSource'>
<property name="files" value="/mo/App/i18n/" />
</bean>
but that didnt work. I have tried a bunch of other things as well which hasnt worked.
I dont want a new bean, I want the first declaration to actually run, initialize the bean and then my second declaration to call a method on that bean.
Is this not possible?
I guess you may want this
<bean id="myBean" class="com.acme.MyClass" init-method="yourInitMethod">
<property ...>
</bean>
Init-method will be called after injecting all properties and after constructor.
I research using transactional annotation in Spring + Hibernate application.
I had problem with using annotation.
I had so problem:
No Hibernate Session bound to thread
my partner to advice me use this filter in web.xml:
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
after I made it problem was resolved. He said me that always when he uses #Transactional annotation he writes this filter.
But in my old application I found using #Transactional without this filter. And it is working application.
Who can explain me it?
application which doesn't work without filter described here:
HTTP Status 500 - Request processing failed; nested exception is org.hibernate.HibernateException: No Hibernate Session bound to thread
update:
model class:
#Entity
#Table(name = "RECORDS")
public class Record
{
#Id
#Column(name = "ID")
#GeneratedValue(strategy = GenerationType.AUTO)
private int recordId;
#Column(name = "VALUE1")
private String vol1;
#Column(name = "VALUE2")
private String vol2;
#Column(name = "VALUE3")
private String vol3;
//////////
get and set
}
update
trace:
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/crud] threw exception [Request processing failed; nested exception is org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here] with root cause
org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
at org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63)
at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:544)
at com.wp.crud.dao.MainDaoImpl.getAllRecords(MainDaoImpl.java:49)
at com.wp.crud.controller.MainServiceImpl.getAllRecords(MainServiceImpl.java:50)
at com.wp.crud.controller.MainController.setupForm(MainController.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:213)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
my java code:
controller method
#RequestMapping(value = "/index")
public String setupForm()
{
mainService.getAllRecords());
}
service interface
#Transactional
public interface MainService
{
public List<Record> getAllRecords();
}
service impl
#Service("mainService")
#Transactional
public class MainServiceImpl implements MainService
{
#Autowired
private MainDao mainDao;
#Transactional
public List<Record> getAllRecords()
{
return mainDao.getAllRecords();
}
}
Configuration:
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
data.xml
<!-- Настраивает управление транзакциями с помощью аннотации #Transactional -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- Менеджер транзакций -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<!-- Настройки бина dataSource будем хранить в отдельном файле -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" p:location="/WEB-INF/jdbc.properties" />
<!-- Непосредственно бин dataSource -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}" />
<!-- Настройки фабрики сессий Хибернейта -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.connection.charSet">UTF-8</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
root-context.xml
<context:component-scan base-package="com.wp.crud.dao"/>
<context:component-scan base-package="com.wp.crud.controller"/>
<!--
Файл с настройками ресурсов для работы с данными (Data Access Resources)
-->
<import resource="data.xml"/>
servlet-context.xml
<annotation-driven />
<!-- Всю статику (изображения, css-файлы, javascript) положим в папку webapp/resources и замаппим их на урл вида /resources/** -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Отображение видов на jsp-файлы, лежащие в папке /WEB-INF/views -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<!-- Файл с настройками контроллеров -->
<beans:import resource="controllers.xml" />
controllers.xml
<context:component-scan base-package="com.wp.crud.controller"/>
P.S.
Services located in controller package.
If you need, or want to use, the OpenSessionInViewFilter depends on your code. If you use your domain objects in your view and have lazy loading collections (the default) or references you will need this filter. By default the hibernate session is gone after finishing the #Transactional, however to perform lazy-loading a hibernate session is needed. The OpenSessionInViewFilter keeps the session(s) open until the view has been rendered.
If you don't have anything lazy or have specific queries/methods to retrieve all the data needed to render the view (i.e. force eager fetching of collection or objects with a HQL query) you don't need an OpenSessionInViewFilter.
So whether you need it or not depends on your use-case and technology choice.
The problem in your case is the fact that you are scanning the same package twice. This leads to duplicate bean instances (one in the ContextLoaderListener and one in the DispatcherServlet the first is the bean you want to use but due to the duplication the second is the one you get). The first is the one with transactions applied.
Change your component scan elements to the following
root-context.xml
<context:component-scan base-package="com.wp.crud">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
controllers.xml
<context:component-scan base-package="com.wp.crud" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
This will make the ContextLoaderListener load everything BUT #Controller annotated beans and the DispatcherServlet loads only #Controller annotated beans.
You should mark necessary methods with #Transactional to define where to start/end transactions.
In your application context you should define that it's annotation driven and define base package to scan. Thus Spring scans the packages and wraps methods marked as #Transactional with Proxies to start and commit/rollbacck transactions.
i have this exception
java.lang.NullPointerException
cz.xkadle21.dip.dao.ADiHibernateGenericDAO.findByCriteria(ADiHibernateGenericDAO.java:116)
cz.xkadle21.dip.dao.impl.DiUserDAO.findUserByUsername(DiUserDAO.java:86)
cz.xkadle21.dip.service.impl.DiUserContextSecurityService.loadUserByUsername(DiUserContextSecurityService.java:47)
cz.xkadle21.dip.service.impl.DiUserContextSecurityService.loadUserByUsername(DiUserContextSecurityService.java:1)
I was following this tutorial Spring Security 3 database authentication with Hibernate
and got "No bean named ... is defined" error. So i moved beans from dispatcher-servlet.xml to applicationContext-common-business.xml and change loading in web.xml
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext-common-business.xml
/WEB-INF/applicationContext-security.xml
</param-value>
</context-param>
<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>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Beans in despatcher-servlet.xml are loading with component-scan and are injecting sessionFactory automaticaly and properly. But bean in applicationContext-common-business.xml not.
applicationContext-common-business.xml
<bean name="userDetailsService"
class="cz.xkadle21.dip.service.impl.DiUserContextSecurityService" >
<constructor-arg ref="userDAO" />
<constructor-arg ref="securityUserFactory" />
</bean>
<bean id="securityUserFactory" class="cz.xkadle21.dip.factory.impl.DiSecurityUserFactory" />
<bean id="userDAO" class="cz.xkadle21.dip.dao.impl.DiUserDAO" />
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="${hibernate.connection.driver_class}"
p:url="${hibernate.connection.url}" p:username="${hibernate.connection.username}"
p:password="${hibernate.connection.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<!-- <prop key="hibernate.hbm2ddl.auto">update</prop> -->
</props>
</property>
</bean>
UserDetailsService is injected via constructor, but how to inject sessionFactory to userDAO? SessionFactory is defined in ADiHibernateGenericDAO and all DAOs extend the abstract ADiHibernateGenericDAO.The exception above is thrown on SessionFactory, which is not injected.
Thanks for any response.
Mate, I don't see any Transaction Manager or
< tx:annotation-driven />
written anywhere in your bean configuration file. You should put it there if you already haven't. That might be the problem.
You haven't shown us your DiUserDAO class, but assuming you have a setter in it for setSessionFactory(), you could simply change your XML mapping to be like:
<bean id="userDAO" class="cz.xkadle21.dip.dao.impl.DiUserDAO">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Alternatively you could modify your DiUserDAO class to mark the SessionFactory field as #Autowired.
The same solution applies to any other beans that need to access this bean.