I am working with GWT and a Spring server. I have an project that I am using for a number of projects that has Spring annotations (#Repository, #Service, #Component etc.) that work in other webapps and projects but when I integrate Spring with GWT the dependency injection is failing saying that the bean doesn't have a matching type.
org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.xxx.yy.api.phone.call.PhoneCallDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#javax.annotation.Resource(mappedName=, shareable=true, description=, name=, type=class java.lang.Object, lookup=, authenticationType=CONTAINER)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:924)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:793)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:438)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:416)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:549)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:150)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:303)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:385)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:284)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
at org.mortbay.jetty.handler.ContextHandler.startContext(ContextHandler.java:543)
at org.mortbay.jetty.servlet.Context.startContext(Context.java:136)
at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1220)
at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:513)
at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:448)
at com.google.gwt.dev.shell.jetty.JettyLauncher$WebAppContextWithReload.doStart(JettyLauncher.java:468)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:39)
at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
at org.mortbay.jetty.handler.RequestLogHandler.doStart(RequestLogHandler.java:115)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:39)
at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
at org.mortbay.jetty.Server.doStart(Server.java:222)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:39)
at com.google.gwt.dev.shell.jetty.JettyLauncher.start(JettyLauncher.java:672)
at com.google.gwt.dev.DevMode.doStartUpServer(DevMode.java:509)
at com.google.gwt.dev.DevModeBase.startUp(DevModeBase.java:1068)
at com.google.gwt.dev.DevModeBase.run(DevModeBase.java:811)
at com.google.gwt.dev.DevMode.main(DevMode.java:311)
The DAOs and services are correctly annotated because this same project is being used in another webapp as I said above. Here is my application context:
<?xml version="1.0" encoding="UTF-8"?>
...
<!-- This line sets up the fact that we can use annotations throughout -->
<context:annotation-config />
<!-- This line tells the Spring boot-strapper where to scan for any objects
that are marked with annotations such as #Repository or #Service or #Component -->
<context:component-scan
base-package="com.xxx.yyy, com.xxx.yyy.api, com.xxx.zzz.api, com.xxx.www, com.gwtplatform.dispatch.server.spring" />
<!-- NOTE: Properties are LAST ONE WINS. Meaning that if there are duplicate
properties the one that is loaded LAST will be used. Because of this we should
make the JNDI name *LAST* This particular class (bean) can be found in the
maher-spring-extension project and it was coded so we can use JNDI to find
an environment specific configuration file. We use these for things such
as the database, log file directories or anything that is specific to that
particular environment. This enables us to be able to build ONE war file
and deploy it to any server and so long as that server environment is configured
with the appropriate configuration file. (example: we configure the STAGE
system to point to the STAGE database and put that properties file somewhere
on that machine and then configure it in the Tomcat JNDI system. Then this
application will find that file and load the properties overwriting any of
the previously set properties (LAST ONE WINS)) -->
<bean
class="org.springframework.beans.factory.config.JndiAwarePropertyPlaceholderConfigurer"
init-method="initialize">
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="ignoreResourceNotFound" value="true" />
<property name="locations">
<list>
<value>classpath:application.properties</value>
<value>classpath:local.properties</value>
<!-- these properties are environment specific and are bound in JNDI.
If there is no entry then it will gracefully ignore them since we set ignoreUnresolvablePlaceholders
to true -->
<value>file:${IVRProperties}</value>
</list>
</property>
</bean>
<!-- Here we are configuring our server module for the GWTP -->
<bean id="serverModule" class="com.xxx.yyy.gwt.server.spring.ServerModule" />
<!-- Here we configure the logger that will be used by the GWTP -->
<bean id="logger"
class="com.gwtplatform.dispatch.server.spring.LoggerFactoryBean">
<constructor-arg>
<bean class="java.util.logging.Logger" factory-method="getAnonymousLogger">
<property name="level">
<value>INFO</value>
</property>
</bean>
</constructor-arg>
</bean>
<!-- Here is our data source. This is the only place you will see anything
to do with a database connection -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver.class}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="maxActive" value="${jdbc.maxActive}" />
</bean>
<!-- Used to stamp every entity that has a createdAt or updatedAt field
on insert and update
<bean id="entityInterceptor" class="com.maher.ivr.server.interceptor.EntityInterceptor"/> -->
<!-- Here we configure the Session Factory. -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="schemaUpdate" value="${hibernate.schema.update}" />
<!-- <property name="entityInterceptor" ref="entityInterceptor"/> -->
<property name="packagesToScan" value="com.xxx.yyy, com.xxx.zzz.api" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.query.substitutions">${hibernate.query.substitutions}</prop>
<prop key="hibernate.bytecode.use_reflection_optimizer">${hibernate.bytecode.use.optimizer}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.generateDdl">${hibernate.generateDdl}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.cache.provider_class">${hibernate.cache.provider}</prop>
</props>
</property>
</bean>
<!-- Here we configure the Transaction manager. -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- Here we enable the transaction manager to be picked up by Aspects.
Because of this we can simply add a #Transactional annotation to our service
classes and all aspects of the transactions are handled for us, such as Rollback,
Commit etc... -->
<bean
class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" />
<bean id="transactionInterceptor"
class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property name="transactionManager" ref="transactionManager" />
<property name="transactionAttributeSource">
<bean
class="org.springframework.transaction.annotation.AnnotationTransactionAttributeSource" />
</property>
</bean>
<bean
class="org.springframework.transaction.interceptor.TransactionAttributeSourceAdvisor">
<property name="transactionInterceptor" ref="transactionInterceptor" />
</bean>
<bean id="velocityEngine"
class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="velocityProperties">
<value>
resource.loader=class
class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
</value>
</property>
</bean>
I'm not sure if the problem is that the classes are part of a separate project that is being included with the GWT project but I don't see how that would be an issue. I can define all the beans manually in the applicationContext.xml but that gets tedious and there are a lot to define because I need to define them for every single class that is injected which is a lot.
What do you mean by
the classes are part of a separate project that is being included with the GWT project ?
It looks like the classes that are included are not visible to the spring container.
Related
I have a project setup (the snippets here are from a demo project I have created on GitHub https://github.com/ashishmarwal/self-populating-cache-issue) where a raw eh-cache cache is declared in the ehcache config (ehcache.xml).
<cache name="alphabet-description-cache"
eternal="false"
maxElementsInMemory="1000"
memoryStoreEvictionPolicy="LRU"
overflowToDisk="false"
timeToLiveSeconds="300"
timeToIdleSeconds="300" />
Spring bean descriptor then uses that raw cache to create a decorated (SelfPopulatingCache) using a CacheEntryFactory:
<bean id="springCacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="cacheManager"/>
</bean>
<!--Creating a decorated cache instance using the raw cache cinfigured in ehcache.xml -->
<bean id="alphabetDescriptionCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean">
<property name="cacheManager" ref="cacheManager"/>
<property name="cacheName" value="alphabet-description-cache"/>
<property name="cacheEntryFactory" ref="alphabetDescriptionCacheEntryFactory"/>
</bean>
<bean id="alphabetDescriptionCacheEntryFactory" class="com.marwals.ashish.issues.selfpopulatingcache.AlphabetDescriptionCacheEntryFactory" />
We also have a test-context.xml which is used for unit testing and declares a cacheManager as well as the decorated cache (in my perspective I have given different names to these cache managers):
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="cacheManagerName" value="self-populating-cache-issue-demo-test"/>
<property name="shared" value="true"/>
<property name="acceptExisting" value="false"/>
<property name="configLocation" value="classpath:/ehcache.xml"/>
</bean>
<bean id="springCacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="cacheManager"/>
</bean>
<bean id="alphabetDescriptionCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean">
<property name="cacheManager" ref="cacheManager"/>
<property name="cacheName" value="alphabet-description-cache"/>
<property name="cacheEntryFactory" ref="alphabetDescriptionCacheEntryFactory"/>
</bean>
<bean id="alphabetDescriptionCacheEntryFactory" class="com.marwals.ashish.issues.selfpopulatingcache.AlphabetDescriptionCacheEntryFactory" />
The problem here is that if I have two different tests each loading either the main or the test-context bean descriptor, I run into an incumbent cache issue:
Error creating bean with name 'alphabetDescriptionCache' defined in class path resource [test-context.xml]: Invocation of init method failed;
nested exception is net.sf.ehcache.CacheException: Cannot replace alphabet-description-cache It does not equal the incumbent cache.
Any ideas what could be wrong here? Debugging the code reveals that I have two different cache instance for the same raw cache which is then raised as an error by EhCache's cache manager.
I have created a git repo demonstrating this problem:
https://github.com/ashishmarwal/self-populating-cache-issue
Thanks!!!
You explicitly requested a shared cache manager in your Spring configuration
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="cacheManagerName" value="self-populating-cache-issue-demo"/>
<property name="shared" value="true"/> <!-- here -->
<property name="acceptExisting" value="false"/>
<property name="configLocation" value="classpath:/ehcache.xml"/>
</bean>
This means Ehcache will always return the same CacheManager for a given configuration. In your case (and generally) you don't want that.
Just setting shared to false solves your problem.
I am implementing Spring Security in project. I have reached an impasse stuck here since hours.
I am getting this error
Error creating bean with name 'org.springframework.security.authentication.dao.DaoAuthenticationProvider#0': Cannot resolve reference to bean 'UserDAOImpl' while setting bean property 'userDetailsService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'myUserDetailService' is defined
The project setup is very simple
spring-security.xml
<authentication-manager>
<authentication-provider user-service-ref="myUserDetailService">
</authentication-provider>
</authentication-manager>
dispatcher-servlet.xml
<context:component-scan base-package="app.com,app.com.controller,app.com.dao,app.com.service,app.com.model"/>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"
p:basename="messages"/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/view/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
ApplicationContext.xml
<context:annotation-config />
<!-- <context:property-placeholder> XML element automatically registers a new PropertyPlaceholderConfigurer
bean in the Spring Context. -->
<context:property-placeholder location="classpath:database.properties" />
<!-- enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="hibernateTransactionManager"/>
<!-- Creating DataSource -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<!-- To persist the object to database, the instance of SessionFactory interface is created.
SessionFactory is a singleton instance which implements Factory design pattern.
SessionFactory loads hibernate.cfg.xml and with the help of TransactionFactory and ConnectionProvider
implements all the configuration settings on a database. -->
<!-- Configuring SessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>app.com.model.User</value>
<value>app.com.model.Roles</value>
<value>app.com.BaseEntity</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
</bean>
<!-- Configuring Hibernate Transaction Manager -->
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
CustomUserDetailsService.java
#Service("myUserDetailService")
#Transactional
public class CustomUserDetailsService implements UserDetailsService {
#Autowired
private UserDAO userDAO;
/*#Override
public UserDetails loadUserByUsername(String arg0)
throws UsernameNotFoundException, DataAccessException {
// TODO Auto-generated method stub
return null;
}
}
I also tried declaring the bean in both dispatcher-servlet.xml & application-context.xml it doesn't work
checked the context-component base package. It is scanning all the other classes present just fine. When I remove myUserDetailService from authentication provider the server starts just fine without any error.
I am really tired. Can anyone please help me in fixing this?
the reason why you got this working after moving the definitions to your context file is because in spring, the definitions inside the dispatcher servlet are only visible to mvc, and definitions inside context are global (to servlet and security), here is a page where its clearly explained https://weblogs.java.net/blog/sgdev-blog/archive/2014/07/05/common-mistakes-when-using-spring-mvc
phew... got it working.
Moved
<context:component-scan base-package="app.com,app.com.controller,app.com.dao,app.com.service,app.com.model"/>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"
p:basename="messages"/>
from dispatcher-servlet to application-context.xml
Would anyone care to tell why it started working?
We are currently using Spring 3 with hibernate 4.4 in our project.
A snippet of my database config xml looks as follows
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass">
<value>${jdbc.driver.className}</value>
</property>
<property name="jdbcUrl">
<value>${jdbc.url}</value>
</property>
<property name="user">
<value>${jdbc.username}</value>
</property>
<property name="password">
<value>${jdbc.password}</value>
</property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.hibernate.dialect}</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.jdbc.batch_size">20</prop>
<prop key="hibernate.current_session_context_class">managed</prop>
</props>
</property>
<property name="packagesToScan" value="com.sample.entity" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<tx:annotation-driven />
While we were testing our war , we came across this exception .
13:27:19,511 ERROR TransactionInterceptor:419 - Application exception overridden by rollback exception
org.springframework.beans.factory.BeanCreationNotAllowedException:
Error creating bean with name 'transactionManager': Singleton bean creation not allowed
while the singletons of this factory are in destruction (Do not request a bean from a
BeanFactory in a destroy method implementation!)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:212)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.transaction.interceptor.TransactionAspectSupport.determineTransactionManager(TransactionAspectSupport.java:248)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:100)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
I am unable to figure out if this is because of the destroy-method =close mentioned in the config file . I am also using the #Transactional annotation at both the Service layer and the database layer . Will this cause any issue?
We were trying to test a scenario where in multiple people (around 150) are all trying to access our application at the same time.
Kindly help me out.. Please do let me know, If more details are needed.
Thanks
As the spring doc says in Section 3.6.1.5
The order of startup and shutdown invocations can be important. If a "depends-on" relationship exists between any two objects, the dependent side will start after its dependency, and it will stop before its dependency. However, at times the direct dependencies are unknown. You may only know that objects of a certain type should start prior to objects of another type. In those cases, the SmartLifecycle interface defines another option, namely the getPhase() method as defined on its super-interface, Phased.
So you need the bean to implement the SmartLifeCycle, Javadoc for SmartLifeCycle Interface 1: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-lifecycle-processor.
Hope this helps !!
Since three days i am trying to get my Spring-Hibernate programs run. i had really tough time finding the involved dependencies due to version difference between hibernate2 and hibernate3.
Finally i was able to run program with following set of dependencies
cglib-nodep-2.1_3.jar
commons-collections.jar
commons-dbcp.jar
commons-pool.jar
commons-logging.jar
dom4j-1.4.jar
ehcache-1.6.0-beta1.jar
hibernate-3.1.3.jar
hsqldb.jar
jta.jar log4j-1.2.9.jar
mysql-connector-java-5.0.8-bin.jar
org.springframework.orm-3.1.0.M1.jar
org.springframework.transaction-3.1.0.M1.jar
spring-2.5.6.jar
spring-beans-2.0.4.jar
now after two days of efforts when i was able to manage the above mentioned dependencies i tried building similar program but it is throwing following error.I tried online for solution but the solution which i found there is not correct version of spring and hibernate ...Can any one tell me correct cause of exception and also correct version of the Spring and hibernate
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myRecordDAO' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'hibernateTemplate' while setting bean property 'hibernateTemplate'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateTemplate' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Initialization of bean failed; nested exception is java.lang.reflect.MalformedParameterizedTypeException
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:275)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:104)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1245)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1010)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at java.security.AccessController.doPrivileged(Native Method)
I am also adding my application 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/subhash"/>
<property name="username" value="root"/>
<property name="password" value=""></property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource"><ref local="dataSource"/></property>
<property name="mappingResources">
<list>
<value>MyRecord.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
<prop key="show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory"><ref local="sessionFactory"/></property>
</bean>
<bean id="myRecordDAO" class="com.shoesobjects.MyRecordDAOHibernateWithSpring">
<property name="hibernateTemplate"><ref local="hibernateTemplate"/></property>
</bean>
</beans>
a)
Note
As of Spring 3.0, Spring requires Hibernate 3.2 or later.
Source:
Spring 3.1.x Reference >
Hibernate
b)
org.springframework.orm-3.1.0.M1.jar
org.springframework.transaction-3.1.0.M1.jar
spring-2.5.6.jar
spring-beans-2.0.4.jar
Do you really think mixing current pre-release versions (3.1.x) with ancient versions (2.0.4 was released in 2007) is a good idea?
As matt says: use a dependency managements system like Maven, what you are dealing with is jar hell. Here's an article about referencing Spring 3.x artifacts from maven:
Obtaining Spring 3 Artifacts with
Maven
I suggest using a dependency management tool like Maven or Apache Ivy so you don't have to handle sorting through the dependencies and required versions on your own.
Hibernate docs on using with Maven
Got my problem resolved ...As pointed by Sean it was due to mixing different versions of spring and hibernate. Message for other newbies is please use latest version of spring and hibernate.As of Spring 3.0, Spring requires Hibernate 3.2 or later.one should never mix old and new version.
Here's a simple file that worked for me, I used transaction manager and not template.
<bean id="mySqlDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/stackoverflow" />
<property name="user" value="root" />
<property name="password" value="******" />
<property name="maxPoolSize" value="50" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="mySqlDataSource" />
<property name="mappingResources">
<list>
<value>Post.hbm.xml</value>
<value>Tag.hbm.xml</value>
<value>User.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect
</value>
<!--
hibernate.connection.provider_class =
org.hibernate.connection.C3P0ConnectionProvider
hibernate.hbm2ddl.auto=update
hibernate.current_session_context_class=thread
-->
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
<!--
<property name="dataSource" ref="mySqlDataSource"/>
-->
</bean>
Also, I think the hibernate download package comes with separate folders that indicate what its specific dependencies are. As for the interrelation between hibernate and spring, I think you will have to use some dependency management tool as others have suggested. I do not think maven is a convenient tool. Just don't ever depart from maven's expected project structure and you should be fine.
I'm trying to add one more database/schema/persistenceUnit in my project and I'm receiving the error:
No unique bean of type [javax.persistence.EntityManagerFactory] is defined: expected single bean but found 2
I google/api allot and could not found why spring is complaining about my configuration.
Here is part of my applicationContext.xml
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="transactionManager" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="${show.hibernate.sql}" />
<property name="generateDdl" value="false" />
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" />
</bean>
</property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${database.driver}" />
<property name="url" ...
<property name="testOnBorrow" value="true" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="entityManagerFactoryREST" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSourceREST" />
<property name="persistenceUnitName" value="REST" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="${show.hibernate.sql}" />
<property name="generateDdl" value="false" />
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" />
</bean>
</property>
</bean>
<bean id="dataSourceREST" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${database.driver}" />
...
<property name="testOnBorrow" value="true" />
</bean>
<bean id="transactionManagerREST" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactoryREST" />
</bean>
<tx:annotation-driven transaction-manager="REST"/>
<tx:annotation-driven transaction-manager="transactionManager"/>
Some questions:
Do I need to have two tx:annotation-driven ?
Do I need to specify persistenceUnitName in the factory ?
I'm putting some notes of my digg in spring forum (LINK)
Well thats it... any help will be glad!
With Spring, you need to have only one EntityManagerFactory.
What you are looking for is describe in the Spring documentation at the chapiter 13.5.1.4 : "Deals with multiple persitence units"
I copy/paste the text :
"13.5.1.4 Dealing with multiple persistence units
For applications that rely on multiple persistence units locations, stored in various JARS in the classpath, for example, Spring offers the PersistenceUnitManager to act as a central repository and to avoid the persistence units discovery process, which can be expensive. The default implementation allows multiple locations to be specified that are parsed and later retrieved through the persistence unit name. (By default, the classpath is searched for META-INF/persistence.xml files.)
<bean id="pum" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="persistenceXmlLocations">
<list>
<value>org/springframework/orm/jpa/domain/persistence-multi.xml</value>
<value>classpath:/my/package/**/custom-persistence.xml</value>
<value>classpath*:META-INF/persistence.xml</value>
</list>
</property>
<property name="dataSources">
<map>
<entry key="localDataSource" value-ref="local-db"/>
<entry key="remoteDataSource" value-ref="remote-db"/>
</map>
</property>
<!-- if no datasource is specified, use this one -->
<property name="defaultDataSource" ref="remoteDataSource"/>
</bean>
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitManager" ref="pum"/>
<property name="persistenceUnitName" value="myCustomUnit"/>
</bean>
The default implementation allows customization of the PersistenceUnitInfo instances, before they are fed to the JPA provider, declaratively through its properties, which affect all hosted units, or programmatically, through the PersistenceUnitPostProcessor, which allows persistence unit selection. If no PersistenceUnitManager is specified, one is created and used internally by LocalContainerEntityManagerFactoryBean."
This exceptions means that you are trying to autowire EntityManagerFactory by type. Do you have any #Autowired annotation in your code?
Aslo, when using #PersistenceContext, set the unit attribute correctly. And (I'm not sure if this is a proper thing to do) - try setting the name attribute to your respective factory name.
Also, check if you haven't copy-pasted incorrectly the REST transaction manager - now there is no such bean REST
Ensure all of your #PersistenceContext specify unitName. I haven't figured out how to tell Spring that a particular EMF or PersistenceUnit is the default. I thought specifying primary="true" on the default EMF would work but doesn't appear to
Do I need to specify persistenceUnitName in the factory ?
If you've got multiple persistence units, you do need to specify which ones the factories will use.
More to the heart of the matter, see SPR-3955. To summarize, versions prior to Spring 3.0M4 do not support multiple transaction managers with #Transactional. Nor do I believe it honors the "unitName" attribute for #PersistenceContext, so you can't specify that either.
For an example of how I worked around this by explicitly injecting EntityManagerFactorys and using AOP to re-enable #Transactional, see my sample app