Spring. Access session Bean in my CustomDataSource getConnection method - java

Does anybody know how to access a session scoped bean in a DataSource getConnection?
I decided to implement a separate database schema for each client (Multi-tenancy) and I found this very promising article: Multitenancy using Spring and PostgreSQL, and have been trying to implement what it says for a while.
As you can see in the comments (and I'm stuck just like the others), it doesn't work because of a java.lang.IllegalStateException. Also found this question where you can see the same thing, in the last comment.
The answer the author (gargii) gives is this:
The error message is probably a very good desciption of the state you are in. Try to think of it. Focus on threads. Which thread gets the original request? Which thread fails with the error? Try to debug the RequestContextHolder class. This is the place where the session-magic is actually done (using ThreadLocal).
Well... I tried to debug but didn't get nowhere, I've seen dozens of pages trying to solve the problem, but still haven’t found a solution.
I always get this exception (I've copied the complete trace at the end):
2013-10-08 08:47:37,232 [localhost-startStop-1] ERROR org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in file [C:\Users\ely\Documents\Desarrollo\Spring\springsource\vfabric-tc-server-developer-2.9.2.RELEASE\base-instance\wtpwebapps\TestMultiTenant\WEB-INF\classes\META-INF\spring\applicationContext.xml]: Invocation of init method failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.tenantContext': Scope 'session' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
In Short, this is what I’ve got:
A security filter that executes before anything else (applicationContext-Security.xml):
<custom-filter before="FIRST" ref="tenantFilter" />
The filter is:
public class TenantFilter implements Filter {
private TenantContext tenantContext;
private TenantRepository tenantRepository;
...
applicationContext.xml:
<bean id="tenantFilter" class="com.i4b.test1.core.TenantFilter">
<property name="tenantContext" ref="tenantContext" />
<property name="tenantRepository" ref="tenantRepository" />
</bean>
TenantContext has:
#Component
#RooJavaBean
#RooToString
#Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class TenantContext {
private Tenant tenant;
private String idSchema;
}
(Note it’s not a RooEntity or RooActiveRecord. I’m just using #RooJavaBean and #RooToString to have setters, getters and toString created automatically)
With it’s mandatory configuration at web.xml:
<!-- ADDED FOR MULTI TENANCY START -->
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<!-- MULTI TENANCY END -->
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
And applicationContext.xml:
<bean id="tenantContext" class="com.i4b.test1.core.TenantContext" scope="session">
<aop:scoped-proxy />
</bean>
There is also:
#Component
public class TenantAwareDataSource extends BasicDataSource {
#Autowired
private TenantContext tenantContext;
// [tenant,schema] to [DataSource] mapping
private final Map<String, BasicDataSource> schemaToDataSource = new HashMap<String, BasicDataSource>();
...
#Override
public Connection getConnection() throws SQLException {
BasicDataSource determineTargetDataSource = determineTargetDataSource();
return determineTargetDataSource.getConnection();
}
This class is configured in the applicationContext.xml:
<bean class="com.i4b.test1.core.TenantAwareDataSource" destroy-method="close" id="dataSource">
<property name="driverClassName" value="${database.driverClassName}"/>
<property name="url" value="${database.url}"/>
<property name="username" value="${database.username}"/>
<property name="password" value="${database.password}"/>
<property name="testOnBorrow" value="true"/>
<property name="testOnReturn" value="true"/>
<property name="testWhileIdle" value="true"/>
<property name="timeBetweenEvictionRunsMillis" value="1800000"/>
<property name="numTestsPerEvictionRun" value="3"/>
<property name="minEvictableIdleTimeMillis" value="1800000"/>
<property name="validationQuery" value="SELECT version();"/>
</bean>
If I remove the #Autowired from "TenantAwareDataSource" shown code, it doesn't give me the exception, but doesn't really work. hahaha. tenantContext is always null because it's not the session bean anymore.
By the way. This application was created using the following versions (pom.xml):
<properties>
<aspectj.version>1.7.2</aspectj.version>
<java.version>7</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<roo.version>1.2.4.RELEASE</roo.version>
<slf4j.version>1.7.5</slf4j.version>
<spring.version>3.2.3.RELEASE</spring.version>
<spring-security.version>3.1.0.RELEASE</spring-security.version>
</properties>
At last, the complete exception is:
2013-10-08 08:47:37,232 [localhost-startStop-1] ERROR org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in file [C:\Users\ely\Documents\Desarrollo\Spring\springsource\vfabric-tc-server-developer-2.9.2.RELEASE\base-instance\wtpwebapps\TestMultiTenant\WEB-INF\classes\META-INF\spring\applicationContext.xml]: Invocation of init method failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.tenantContext': Scope 'session' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:529)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:741)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4887)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5381)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:657)
at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1637)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
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:724)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in file [C:\Users\ely\Documents\Desarrollo\Spring\springsource\vfabric-tc-server-developer-2.9.2.RELEASE\base-instance\wtpwebapps\TestMultiTenant\WEB-INF\classes\META-INF\spring\applicationContext.xml]: Invocation of init method failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.tenantContext': Scope 'session' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1482)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:439)
at org.springframework.beans.factory.BeanFactoryUtils.beansOfTypeIncludingAncestors(BeanFactoryUtils.java:277)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.detectPersistenceExceptionTranslators(PersistenceExceptionTranslationInterceptor.java:139)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.<init>(PersistenceExceptionTranslationInterceptor.java:79)
at org.springframework.dao.annotation.PersistenceExceptionTranslationAdvisor.<init>(PersistenceExceptionTranslationAdvisor.java:71)
at org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor.setBeanFactory(PersistenceExceptionTranslationPostProcessor.java:85)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeAwareMethods(AbstractAutowireCapableBeanFactory.java:1502)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1470)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
... 24 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.tenantContext': Scope 'session' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:343)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:34)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.getTarget(CglibAopProxy.java:663)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:614)
at com.i4b.test1.core.TenantContext$$EnhancerByCGLIB$$c51ab566.getTenant(<generated>)
at com.i4b.test1.core.TenantContext_Roo_JavaBean.ajc$interMethodDispatch1$com_i4b_test1_core_TenantContext_Roo_JavaBean$com_i4b_test1_core_TenantContext$getTenant(TenantContext_Roo_JavaBean.aj)
at com.i4b.test1.core.TenantAwareDataSource.currentLookupKey(TenantAwareDataSource.java:77)
at com.i4b.test1.core.TenantAwareDataSource.determineTargetDataSource(TenantAwareDataSource.java:99)
at com.i4b.test1.core.TenantAwareDataSource.getConnection(TenantAwareDataSource.java:216)
at org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider.getConnection(InjectedDataSourceConnectionProvider.java:70)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcServicesImpl.java:242)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:117)
at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:75)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:159)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:131)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1797)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1755)
at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:96)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:914)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:899)
at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:76)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:288)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:310)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1541)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1479)
... 39 more
Caused by: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes(RequestContextHolder.java:131)
at org.springframework.web.context.request.SessionScope.get(SessionScope.java:90)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:329)
... 64 more `

Your DataSource is probably being instantiated long before any request is made (note the bootstrap thread name in your log - [localhost-startStop-1]). So there is actually no SESSION which can be used by Spring to satisfy the SESSION scope.
You need to implement session-scoping manually (via RequestContextHolder) or have the components loosly coupled (e.g. via ApplicationContext#getBean).
What we have done on several projects is to implement TenantContext as ThreadLocal variable (similar to Spring Security's SecurityContext), which is being set and unset by a special servlet Filter. That is by far the best approach as no component will rely on the fact that there is actually an active HTTP request.
To sum this up - you would be better off without any session scoped bean for your particular use case.
Sidenote: If you are using Hibernate, then be aware that there is already a support for multi-tenancy. Other frameworks might support it as well.

Related

Spring JNDI, How do I tell the container where the beans are without code?

I have ben asked to make an enhancement to an older Spring application (I think 2.0 but maybe 2.5) and I know very little about Spring. The application runs under Oracle OC4J as it was given to me, and I am trying to get it to run under Jetty so I can debug it. I imported the project into the latest Spring Tool Suite from its pom.xml and fixed what seemed to be a few minor config issues, and I think it will run under the Spring 4 I am using. I was able to use mvn to build a WAR file and now I am trying to get it to run under Jetty.
When I start it, Jetty runner throws a bunch of exceptions like the one I'll paste below, but the common theme seems to be that it can not resolve my beans. I have found some posts showing how to add naming information into the code, but this code already runs as is and needs to run under the same environment it is running under now after I change it. So I am hesitant to make a change like that. It seems that I could somehow map this in a properties file, but I can't find a way to do that.
I think the important info from the exception below is:
Invocation of init method failed; nested exception is javax.naming.NameNotFoundException; remaining name 'datasource/regcntrllst'
If someone could tell me what's wrong and point me to the appropriate docs I would greatly appreciate it, thanks...
Here is an XML configuration file from src/main/resources/edu called applicationContext-container.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.xsd">
<!--
Provides bean definitions for use in the J2EE container (as opposed to in the standalone test
environment.
-->
<!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -->
<!-- Data Sources -->
<!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -->
<bean id="sisDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="datasource/regcntrllst" />
<property name="resourceRef" value="true" />
</bean>
<!-- Transaction manager outside of app servers -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
Here is the exception:
VJG8WP:jetty-test jarcher$ java -cp jetty-runner-9.3.2.v20150730.jar org.eclipse.jetty.runner.Runner academic-regcntrllst-1.2.10-SNAPSHOT.war
2015-08-03 16:49:17.344:INFO::main: Logging initialized #105ms
2015-08-03 16:49:17.351:INFO:oejr.Runner:main: Runner
2015-08-03 16:49:17.433:INFO:oejs.Server:main: jetty-9.3.2.v20150730
2015-08-03 16:49:21.943:INFO:/:main: No Spring WebApplicationInitializer types detected on classpath
2015-08-03 16:49:22.093:INFO:/:main: Initializing Spring root WebApplicationContext
[ERROR] [2015-08-03 16:49:23,575] [org.springframework.web.context.ContextLoader] - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mitsisStudentService' defined in URL [jar:file:/private/var/folders/z5/m0w5k8z16xq25l_26n_fsl1m0000gn/T/jetty-0.0.0.0-8080-academic-regcntrllst-1.2.10-SNAPSHOT.war-_-any-4602767227392286160.dir/webapp/WEB-INF/lib/csf-common-legacy-2.0.43.jar!/applicationContext-csf-common.xml]: Cannot resolve reference to bean 'hibernateStudentDao' while setting bean property 'studentDao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateStudentDao' defined in URL [jar:file:/private/var/folders/z5/m0w5k8z16xq25l_26n_fsl1m0000gn/T/jetty-0.0.0.0-8080-academic-regcntrllst-1.2.10-SNAPSHOT.war-_-any-4602767227392286160.dir/webapp/WEB-INF/lib/csf-common-legacy-2.0.43.jar!/applicationContext-csf-common.xml]: Cannot resolve reference to bean 'daoFoundation' while setting bean property 'daoFoundation'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'daoFoundation' defined in URL [jar:file:/private/var/folders/z5/m0w5k8z16xq25l_26n_fsl1m0000gn/T/jetty-0.0.0.0-8080-academic-regcntrllst-1.2.10-SNAPSHOT.war-_-any-4602767227392286160.dir/webapp/WEB-INF/lib/csf-orm-2.0.43.jar!/applicationContext-csf-orm-config.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 URL [file:/private/var/folders/z5/m0w5k8z16xq25l_26n_fsl1m0000gn/T/jetty-0.0.0.0-8080-academic-regcntrllst-1.2.10-SNAPSHOT.war-_-any-4602767227392286160.dir/webapp/WEB-INF/classes/applicationContext.xml]: Cannot resolve reference to bean 'mitsisDataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mitsisDataSource' defined in URL [file:/private/var/folders/z5/m0w5k8z16xq25l_26n_fsl1m0000gn/T/jetty-0.0.0.0-8080-academic-regcntrllst-1.2.10-SNAPSHOT.war-_-any-4602767227392286160.dir/webapp/WEB-INF/classes/applicationContext-container.xml]: Invocation of init method failed; nested exception is javax.naming.NameNotFoundException; remaining name 'datasource/regcntrllst'
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1360)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1118)
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.eclipse.jetty.server.handler.ContextHandler.callContextInitialized(ContextHandler.java:798)
at org.eclipse.jetty.servlet.ServletContextHandler.callContextInitialized(ServletContextHandler.java:530)
at org.eclipse.jetty.server.handler.ContextHandler.startContext(ContextHandler.java:771)
at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:342)
at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1368)
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1335)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:735)
at org.eclipse.jetty.servlet.ServletContextHandler.doStart(ServletContextHandler.java:259)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:511)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:132)
at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:114)
at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.doStart(ContextHandlerCollection.java:161)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:132)
at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:114)
at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:132)
at org.eclipse.jetty.server.Server.start(Server.java:405)
at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:106)
at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61)
at org.eclipse.jetty.server.Server.doStart(Server.java:372)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.runner.Runner.run(Runner.java:502)
at org.eclipse.jetty.runner.Runner.main(Runner.java:547)
It looks like the data-source 'datasource/regcntrllst' can't be found.
You need to add this data-source with the same name to your Jetty server. Here's the Configuring DataSources section of the Jetty documentation.

BeanCreationException: Error creating bean with name: Injection of autowired dependencies failed;

I am getting the following error stack when trying to deploy a war using a jetty server I have written.
INFO : jetty.StartJetty - starting jetty using war file ..\serialisation-preview-service\target\serialisation-preview-service-1.3.0-SNAPSHOT.war
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/C:/Users/username/.m2/repository/org/slf4j/slf4j-log4j12/1.6.1/slf4j-log4j12-1.6.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/C:/Users/username/.m2/repository/org/slf4j/slf4j-log4j12/1.6.2/slf4j-log4j12-1.6.2.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
INFO : org.eclipse.jetty.util.log - jetty-7.2.2.v20101205
INFO : org.eclipse.jetty.util.log - Extract jar:file:/U:/Code/Serialisation_Fresh/serialisation-preview-service/target/serialisation-preview-service-1.3.0-SNAPSHOT.war!/ to C:\Users\username\AppData\Local\Temp\jetty-0.0.0.0-8080-serialisation-preview-service-1.3.0-SNAPSHOT.war-_-any-\webapp
INFO : / - Initializing Spring root WebApplicationContext
INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization started
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Fri May 22 09:02:37 BST 2015]; root of context hierarchy
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/applicationContext.xml]
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#d75e99: defining beans []; root of factory hierarchy
INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 1958 ms
WARN : org.eclipse.jetty.util.log - FAILED jsp: java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory
INFO : / - Initializing Spring FrameworkServlet 'appServlet'
INFO : org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'appServlet': initialization started
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Refreshing WebApplicationContext for namespace 'appServlet-servlet': startup date [Fri May 22 09:02:39 BST 2015]; parent: Root WebApplicationContext
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/servlet-context.xml]
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [preview-service-context.xml]
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [dao-context.xml]
INFO : org.springframework.beans.factory.config.PropertyPlaceholderConfigurer - Loading properties file from class path resource [placeit.properties]
INFO : org.springframework.beans.factory.config.PropertyOverrideConfigurer - Loading properties file from class path resource [preview-server-overrideDEV.properties]
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#d61b48: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,myController,org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter#0,previewServerPropertyOverride,org.springframework.beans.factory.config.PropertyOverrideConfigurer#0,labelService,placeit.SerialDataCSVGenerator#0,placeit.DataMatrixGenerator#0,org.springframework.expression.spel.standard.SpelExpressionParser#0,printers,ftp.FtpEmulator#0,placeitPreviewProcess,placeitLabelProcess,placeitHapaProcess,hgdlCompiler,util.DateServiceImpl#0,org.springframework.integration.internalDefaultConfiguringBeanFactoryPostProcessor,org.springframework.scheduling.support.PeriodicTrigger#0,poller,JobFileCreator,rendezvous,PreviewService,org.springframework.integration.transformer.HeaderEnricher#0,org.springframework.integration.transformer.MessageTransformingHandler#0,writeFiles,org.springframework.integration.config.ConsumerEndpointFactoryBean#0,writeFiles2,limitJobs,org.springframework.integration.router.RecipientListRouter#0,writeJobRouter,org.springframework.integration.config.ServiceActivatorFactoryBean#0,createJobFile,createJobFileSA,org.springframework.integration.transformer.HeaderEnricher#1,org.springframework.integration.transformer.MessageTransformingHandler#1,writeJobFile,org.springframework.integration.config.ConsumerEndpointFactoryBean#1,writeJobFile2,org.springframework.integration.file.config.FileWritingMessageHandlerFactoryBean#0,writeJobFile2.adapter,org.springframework.integration.transformer.HeaderEnricher#2,org.springframework.integration.transformer.MessageTransformingHandler#2,writeFmtFile,org.springframework.integration.config.ConsumerEndpointFactoryBean#2,writeFmtFile2,org.springframework.integration.file.config.FileWritingMessageHandlerFactoryBean#1,writeFmtFile2.adapter,org.springframework.integration.config.ServiceActivatorFactoryBean#1,waitForReply,org.springframework.integration.config.ConsumerEndpointFactoryBean#3,generatedPreviewFile,org.springframework.integration.file.config.FileListFilterFactoryBean#0,org.springframework.integration.file.config.FileReadingMessageSourceFactoryBean#0,generatedPreviewFile.adapter,org.springframework.integration.config.TransformerFactoryBean#0,org.springframework.integration.config.ConsumerEndpointFactoryBean#4,org.springframework.integration.config.ServiceActivatorFactoryBean#2,deliverReply,org.springframework.integration.config.ConsumerEndpointFactoryBean#5,aggregationDaoImpl,notificationDaoImpl,parametersDaoImpl,serialisationDaoImpl,templatePreviewDaoImpl,transactionManager,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,entityManagerFactory,org.springframework.jdbc.core.JdbcTemplate#0,org.springframework.jdbc.core.simple.SimpleJdbcTemplate#0,dataSource,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0,nullChannel,errorChannel,_org.springframework.integration.errorLogger,taskScheduler]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory#d75e99
INFO : org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler - Initializing ExecutorService 'taskScheduler'
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#d61b48: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,myController,org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter#0,previewServerPropertyOverride,org.springframework.beans.factory.config.PropertyOverrideConfigurer#0,labelService,placeit.SerialDataCSVGenerator#0,placeit.DataMatrixGenerator#0,org.springframework.expression.spel.standard.SpelExpressionParser#0,printers,ftp.FtpEmulator#0,placeitPreviewProcess,placeitLabelProcess,placeitHapaProcess,hgdlCompiler,util.DateServiceImpl#0,org.springframework.integration.internalDefaultConfiguringBeanFactoryPostProcessor,org.springframework.scheduling.support.PeriodicTrigger#0,poller,JobFileCreator,rendezvous,PreviewService,org.springframework.integration.transformer.HeaderEnricher#0,org.springframework.integration.transformer.MessageTransformingHandler#0,writeFiles,org.springframework.integration.config.ConsumerEndpointFactoryBean#0,writeFiles2,limitJobs,org.springframework.integration.router.RecipientListRouter#0,writeJobRouter,org.springframework.integration.config.ServiceActivatorFactoryBean#0,createJobFile,createJobFileSA,org.springframework.integration.transformer.HeaderEnricher#1,org.springframework.integration.transformer.MessageTransformingHandler#1,writeJobFile,org.springframework.integration.config.ConsumerEndpointFactoryBean#1,writeJobFile2,org.springframework.integration.file.config.FileWritingMessageHandlerFactoryBean#0,writeJobFile2.adapter,org.springframework.integration.transformer.HeaderEnricher#2,org.springframework.integration.transformer.MessageTransformingHandler#2,writeFmtFile,org.springframework.integration.config.ConsumerEndpointFactoryBean#2,writeFmtFile2,org.springframework.integration.file.config.FileWritingMessageHandlerFactoryBean#1,writeFmtFile2.adapter,org.springframework.integration.config.ServiceActivatorFactoryBean#1,waitForReply,org.springframework.integration.config.ConsumerEndpointFactoryBean#3,generatedPreviewFile,org.springframework.integration.file.config.FileListFilterFactoryBean#0,org.springframework.integration.file.config.FileReadingMessageSourceFactoryBean#0,generatedPreviewFile.adapter,org.springframework.integration.config.TransformerFactoryBean#0,org.springframework.integration.config.ConsumerEndpointFactoryBean#4,org.springframework.integration.config.ServiceActivatorFactoryBean#2,deliverReply,org.springframework.integration.config.ConsumerEndpointFactoryBean#5,aggregationDaoImpl,notificationDaoImpl,parametersDaoImpl,serialisationDaoImpl,templatePreviewDaoImpl,transactionManager,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,entityManagerFactory,org.springframework.jdbc.core.JdbcTemplate#0,org.springframework.jdbc.core.simple.SimpleJdbcTemplate#0,dataSource,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0,nullChannel,errorChannel,_org.springframework.integration.errorLogger,taskScheduler]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory#d75e99
INFO : org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler - Shutting down ExecutorService 'taskScheduler'
ERROR: org.springframework.web.servlet.DispatcherServlet - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private dao.TemplatePreviewDao controllers.PreviewHttpController.dao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'templatePreviewDaoImpl': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [dao-context.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [dao-context.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'password' of bean class [org.springframework.jndi.JndiObjectFactoryBean]: Bean property 'password' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
Related cause: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [dao-context.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'password' of bean class [org.springframework.jndi.JndiObjectFactoryBean]: Bean property 'password' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
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:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:609)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:571)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:623)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:491)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:432)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:133)
at javax.servlet.GenericServlet.init(GenericServlet.java:212)
at org.eclipse.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:432)
at org.eclipse.jetty.servlet.ServletHolder.doStart(ServletHolder.java:260)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:55)
at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:762)
at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:244)
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1181)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:584)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:496)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:55)
at org.eclipse.jetty.server.handler.HandlerCollection.doStart(HandlerCollection.java:226)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:55)
at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:93)
at org.eclipse.jetty.server.Server.doStart(Server.java:243)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:55)
at jetty.StartJetty.main(StartJetty.java:56)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private dao.TemplatePreviewDao controllers.PreviewHttpController.dao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'templatePreviewDaoImpl': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [dao-context.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [dao-context.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'password' of bean class [org.springframework.jndi.JndiObjectFactoryBean]: Bean property 'password' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:504)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
... 32 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'templatePreviewDaoImpl': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [dao-context.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [dao-context.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'password' of bean class [org.springframework.jndi.JndiObjectFactoryBean]: Bean property 'password' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:343)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
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:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:844)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:786)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:476)
... 34 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [dao-context.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [dao-context.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'password' of bean class [org.springframework.jndi.JndiObjectFactoryBean]: Bean property 'password' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1325)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1086)
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:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findDefaultEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:531)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:497)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.resolveEntityManager(PersistenceAnnotationBeanPostProcessor.java:658)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.getResourceToInject(PersistenceAnnotationBeanPostProcessor.java:631)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:147)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:340)
... 45 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [dao-context.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'password' of bean class [org.springframework.jndi.JndiObjectFactoryBean]: Bean property 'password' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1361)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1086)
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:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:322)
... 61 more
Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'password' of bean class [org.springframework.jndi.JndiObjectFactoryBean]: Bean property 'password' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:1031)
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:902)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:76)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:58)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1358)
... 69 more
Here is the TemplatePreview class it complains about with an EntityManager define:
#Repository
public class TemplatePreviewDaoImpl implements TemplatePreviewDao {
#PersistenceContext private EntityManager entityManager;
// ...
}
Here is one of my project context files with bean declarations:
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven mode="proxy" transaction-manager="transactionManager"/>
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
<property name="dataSource" ref="dataSource"/>
<property name="persistenceXmlLocation" value="classpath:/META-INF/persistenceOracle.xml"/>
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
</property>
</bean>
<bean class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource"/>
</bean>
<bean class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
<constructor-arg ref="dataSource"/>
</bean>
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean" >
<property name="jndiName" value="java:comp/env/DS_SERIALISATION"/>
</bean>
And the contents of the properties file containing the information for the dataSource:
dataSource.url=jdbc:oracle:thin:#correct_url
dataSource.username=************
dataSource.password=************
dataSource.driverClassName=oracle.jdbc.OracleDriver
entityManagerFactory.persistenceXmlLocation=classpath:/META-INF/persistenceOracle.xml
rendezvous.timeout=-1
The persistenceOracle xml file mentioned here is also accessible so I don't think it's a problem there. I have no idea why Spring cannot autowire the dependencies or why it is having trouble with my dataSource. Any help with this would be much appreciated.
EDIT
My override file exists in a separate project but I can't be sure my war project knows about it. The project that contains the properties file does not have a src folder or anything so I can't add it to the classpath of the war project.
I pass DEV as a VM argument in my run configuration which gets appended when looking for the correct properties file.
What im thinking is that your dataSource is simply instantiating an object of type JndiObjectFactoryBean, then passing that all over the place until somewhere along the line Spring tries to inject the property "password", to which it finds that there is no property "password" for a JndiObjectFactoryBean object.
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean" >
<property name="jndiName" value="java:comp/env/DS_SERIALISATION"/>
</bean>
JNDI is an api which allows you to access a directory via names (see the tutorial here). Instead of returning the JndiObjectFactoryBean object, it should be performing a JNDI lookup based on the jndiName that you are providing.
I think you need to tell the JndiObjectFactoryBean to do the look up and return the JNDI result as your Spring Bean. Consider the below example.
Spring configuration:
<bean id="jndiLookup" class="org.springframework.jndi.JndiObjectLocator">
<property name="jndiName" value="java:comp/env/DS_SERIALISATION"/>
</bean>
<bean id="dataSource" class="com.mypackage.DataSourceLocator">
<property name="jndi" ref="jndiLookup"/>
</bean>
Custom static factory to get object from jndi lookup:
public class DataSourceLocator {
public JndiObjectLocator jndi;
public static Object lookup() {
return jndi.lookup();
}
}
Theres probably a better way out there, but im no expert when it comes to jndi!
After trying many things I decided to try this:
<bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" id="dataSource">
<property name="driverClassName" value="org.h2.Driver"/>
<property name="url" value="jdbc:h2:mem:"/>
<property name="username" value="sa"/>
<property name="password" value=""/>
<property name="testOnBorrow" value="true"/>
<property name="testWhileIdle" value="true"/>
<property name="timeBetweenEvictionRunsMillis" value="300000"/>
Seems to do the trick. Not sure why Jndi doesn't work :S

No lookup on start for datasources in hibernate multi-tenant application

I am currently working on a multi-tenant application using Spring and Hibernate with separate databases.
I would like my application to work even if one of my datasources is inaccessible (in case of problem), so that the other tenants can still access their data. That's why I don't want my application to check the datasources at deployment time. I tried to tell to not look up for datasources at start time :
applicationContext-datasources.xml :
<!-- data source 1 -->
<jee:jndi-lookup id="ds1" jndi-name="jdbc/ds1" resource-ref="true" lookup-on-startup="false" expected-type="javax.sql.DataSource" />
<!-- data source 2 -->
<jee:jndi-lookup id="ds2" jndi-name="jdbc/ds2" resource-ref="true" lookup-on-startup="false" expected-type="javax.sql.DataSource" />
But I get this exception stack :
11:24:10,192 INFO [STDOUT] 2014-11-28 11:24:10,189 - ERROR [main (ContextLoader.java:307) - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myDAO': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in file [applicationContext.xml]: Invocation of init method failed; nested exception is org.springframework.jndi.JndiLookupFailureException: JndiObjectTargetSource failed to obtain new target object; nested exception is javax.naming.NameNotFoundException: jdbc not bound
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in file [applicationContext.xml]: Invocation of init method failed; nested exception is org.springframework.jndi.JndiLookupFailureException: JndiObjectTargetSource failed to obtain new target object; nested exception is javax.naming.NameNotFoundException: jdbc not bound
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:342)
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)
...
Caused by: org.springframework.jndi.JndiLookupFailureException: JndiObjectTargetSource failed to obtain new target object; nested exception is javax.naming.NameNotFoundException: jdbc not bound
at org.springframework.jndi.JndiObjectTargetSource.getTarget(JndiObjectTargetSource.java:139)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:182)
at $Proxy54.getConnection(Unknown Source)
at com.example.MultiTenantConnectionProviderImpl.getConnection(MultiTenantConnectionProviderImpl.java:45)
at com.example.MultiTenantConnectionProviderImpl.getAnyConnection(MultiTenantConnectionProviderImpl.java:31)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl$MultiTenantConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcServicesImpl.java:302)
...
Caused by: javax.naming.NameNotFoundException: jdbc not bound
at org.jnp.server.NamingServer.getBinding(NamingServer.java:529)
at org.jnp.server.NamingServer.getBinding(NamingServer.java:537)
at org.jnp.server.NamingServer.getObject(NamingServer.java:543)
at org.jnp.server.NamingServer.lookup(NamingServer.java:267)
at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:625)
at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:587)
at javax.naming.InitialContext.lookup(InitialContext.java:392)
at org.springframework.jndi.JndiTemplate$1.doInContext(JndiTemplate.java:154)
at org.springframework.jndi.JndiTemplate.execute(JndiTemplate.java:87)
at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:152)
at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:178)
at org.springframework.jndi.JndiLocatorSupport.lookup(JndiLocatorSupport.java:104)
at org.springframework.jndi.JndiObjectLocator.lookup(JndiObjectLocator.java:105)
at org.springframework.jndi.JndiObjectTargetSource.getTarget(JndiObjectTargetSource.java:132)
...
If I set lookup-on-startup with true in applicationContext-datasources.xml, then it works perfectly fine, but I know it won't work the day one of my datasources is inaccessible, even for the other tenant.
Thanks in advance for your help.
I found a way to achieve my goal, but the solution is not perfect.
When I declare my class MultiTenantConnectionProviderImpl, in the method getAnyConnection(), I give a connection from a default database, which is shared by all tenants :
public class MultiTenantConnectionProviderImpl implements MultiTenantConnectionProvider, Stoppable {
#Override
public Connection getAnyConnection() throws SQLException {
return defaultDataSource.getConnection();
}
...
}
And I let ths other methods determine the current tenant.
Then, in applicationContext-datasources.xml, I can declare all other datasources as I wished :
applicationContext-datasources.xml :
<!-- default data source -->
<jee:jndi-lookup id="defaultDatasource" jndi-name="jdbc/defaultDatasource" resource-ref="true" lookup-on-startup="true" expected-type="javax.sql.DataSource" />
<!-- data source 1 -->
<jee:jndi-lookup id="ds1" jndi-name="jdbc/ds1" resource-ref="true" lookup-on-startup="false" expected-type="javax.sql.DataSource" />
<!-- data source 2 -->
<jee:jndi-lookup id="ds2" jndi-name="jdbc/ds2" resource-ref="true" lookup-on-startup="false" expected-type="javax.sql.DataSource" />
That way it works, but it requires a shared database.

Use Tomcat connection pool in JAR (shared conf from web app, spring configuration)

I have a few web applications deployed on Tomcat which all use the same database access configuration from Tomcat connection pool:
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/postgres"/>
<property name="lookupOnStartup" value="true"/>
<property name="proxyInterface" value="javax.sql.DataSource"/>
</bean>
(web.xml in each project and context.xml in Tomcat are set properly, because everything works :)).
I would like to use this connection also with JAR files which run on the same server. In the JAR I also use Spring, but I get the following error if I use above dataSource definition in the code like this:
String[] springConfig = { "file:/var/pro/conf/data-access.xml"};
context = new ClassPathXmlApplicationContext(springConfig);
I get the following error:
Exception in thread "main" java.lang.ExceptionInInitializerError
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:247)
at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:56)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in URL [file:/var/pro/conf/data-access.xml]: Invocation of init method failed; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1482)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:610)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
at com.proj.job.Start.<clinit>(Start.java:73)
... 3 more
Caused by: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:645)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:325)
at javax.naming.InitialContext.lookup(InitialContext.java:392)
at org.springframework.jndi.JndiTemplate$1.doInContext(JndiTemplate.java:154)
at org.springframework.jndi.JndiTemplate.execute(JndiTemplate.java:87)
at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:152)
at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:178)
at org.springframework.jndi.JndiLocatorSupport.lookup(JndiLocatorSupport.java:95)
at org.springframework.jndi.JndiObjectLocator.lookup(JndiObjectLocator.java:105)
at org.springframework.jndi.JndiObjectTargetSource.afterPropertiesSet(JndiObjectTargetSource.java:97)
at org.springframework.jndi.JndiObjectFactoryBean$JndiObjectProxyFactory.createJndiObjectProxy(JndiObjectFactoryBean.java:285)
at org.springframework.jndi.JndiObjectFactoryBean$JndiObjectProxyFactory.access$000(JndiObjectFactoryBean.java:274)
at org.springframework.jndi.JndiObjectFactoryBean.afterPropertiesSet(JndiObjectFactoryBean.java:177)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1541)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1479)
... 15 more
This code will not work if you run it outside Tomcat, that is from main. Tomcat provides initial context factory for JNDI.

spring batch late binding doesn't work on unix

filesTobeParsedHolder contains a map , which based on the key, will return an arrayList object that is a list of file names.
The above spring batch config worked fine on windows. But the same code doesn't work on unix/linux and shows the following error :
ERROR 2013-10-17 03:45:19,851 [SimpleAsyncTaskExecutor-17] AbstractStep - Encountered an error executing the step
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'lazyBindingProxy.generalProfilingLogMRI#sys
init' defined in class path resource [GeneralExtractJobs/generalExtractJob.xml]: Initialization of bean failed; nested exception is
java.lang.IllegalStateException: Cannot bind to placeholder: filesTobeParsedHolder.get(stepExecutionContext['date.as.yyyyMMdd'].co
ncat('.').concat(stepExecutionContext['instance']))
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFac
tory.java:480)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.ja
va:409)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFacto
ry.java:380)
at org.springframework.beans.factory.support.AbstractBeanFactory$2.getObject(AbstractBeanFactory.java:302)
at org.springframework.batch.core.scope.StepScope.get(StepScope.java:150)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
at org.springframework.batch.core.scope.util.PlaceholderTargetSource.getTarget(PlaceholderTargetSource.java:185)
<bean id="generalProfilingLogMRI" class="org.springframework.batch.item.file.MultiResourceItemReader" scope="step">
<property name="resources" value="#{filesTobeParsedHolder.get(stepExecutionContext['date.as.yyyyMMdd'].concat('.').concat(stepExecutionContext['instance']))}"/>
<property name="delegate" ref="generalProfilingLogFileItemReader" />
</bean>

Categories

Resources