With Spring 4.3.5, we have been using an application architecture where we initialize some of the beans at a go and then use the beans as "Reference" for other beans.
Something like this
<bean id="handleUncheckedEndpointExceptionAdvice"
class="com.gehcit.cp.ws.infrastructure.aop.advices.HandleUncheckedEndpointExceptionAdvice">
<constructor-arg ref="exceptionFactory"/>
<property name="exceptionSenderService" ref="exceptionSenderService" />
</bean>
But once we upgraded our library to Spring 5.2.x, we started getting the below exception at Jboss 7.3.1 startup:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'handleUncheckedEndpointExceptionAdvice' defined in ServletContext resource [/WEB-INF/context-web.xml]: Cannot resolve reference to bean 'exceptionSenderService' while setting bean property 'exceptionSenderService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'exceptionSenderService' available
What all I did:
Enabled TRACE logging and found this - 2022-03-05 13:09:39,927 TRACE [org.springframework.beans.factory.annotation.InjectionMetadata] (ServerService Thread Pool -- 65) Processing injected element of bean 'exceptionSenderService': AutowiredFieldElement for private com.gehcit.cp.serviceability.service.ExceptionSenderService com.gehcit.cp.cem.aplix.jms.service.Impl.AplixPublisherQueueServiceImpl.exceptionSender 2022-03-05 13:09:39,927 TRACE [org.springframework.beans.factory.support.DefaultListableBeanFactory] (ServerService Thread Pool -- 65) Returning cached instance of singleton bean 'exceptionSenderServiceImpl' 2022-03-05 13:09:39,927 TRACE [org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor] (ServerService Thread Pool -- 65) Autowiring by type from bean name 'exceptionSenderService' to bean named 'exceptionSenderServiceImpl'
Now the bean is getting initialized but when the reference is being searched, being searched from the Spring cache, we get nothing.
But then we tried shifting the bean initialization from a different xml to the same xml where the bean is being referred and that worked. So we concluded that somehow the cross XML configurations are not working.
Bean being referred from context-web.xml
<?xml version="1.0"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:cxf="http://cxf.apache.org/core"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:oauth2="http://www.springframework.org/schema/security/oauth2"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
http://www.springframework.org/schema/security
https://www.springframework.org/schema/security/spring-security.xsd
http://www.springframework.org/schema/security/oauth2
https://www.springframework.org/schema/security/spring-security-oauth2.xsd">
<task:annotation-driven/>
<!-- Define placeholder for application properties -->
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>/WEB-INF/web.properties</value>
<value>classpath:application.properties</value>
</list>
</property>
</bean>
<!-- Load CXF modules from cxf.jar -->
<import resource="classpath:META-INF/cxf/cxf.xml"/>
<import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>
<import resource="context-cem-web.xml"/>
<!-- define an auto-proxy generator for our advisors -->
<bean
class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator">
<property name="proxyTargetClass" value="false"/>
</bean>
<!-- id generator for exceptions -->
<bean id="exceptionIdGenerator"
class="com.gehcit.cp.ws.infrastructure.exception.HostTimeExceptionIdGenerator">
<property name="prefix" value="CEN"/>
</bean>
<!-- system fault factory -->
<bean id="systemFaultFactory"
class="com.gehcit.cp.ws.infrastructure.exception.StandardSystemFaultFactory">
<property name="exceptionIdGenerator" ref="exceptionIdGenerator"/>
<property name="appendExceptionIdToErrorMessage" value="true"/>
</bean>
<bean id="defaultParamConverterProvider"
class="org.apache.cxf.jaxrs.ext.search.DefaultParamConverterProvider"/>
<!-- factory for mapping runtime exceptions to wire faults -->
<bean id="exceptionFactory"
class="com.gehcit.cp.ws.infrastructure.exception.ExceptionMapperExceptionFactory">
<property name="exceptionMappers">
<list>
<bean
class="com.gehcit.cp.ws.infrastructure.exception.IllegalArgumentFaultFromIllegalArgumentExceptionMapper"/>
<bean
class="com.gehcit.cp.ws.infrastructure.exception.SecurityFaultFromCPSecurityExceptionMapper"/>
<bean
class="com.gehcit.cp.ws.infrastructure.exception.ApplicationFaultFromApplicationErrorMapper"/>
<bean
class="com.gehcit.cp.ws.infrastructure.exception.SystemFaultFromRuntimeExceptionMapper">
<constructor-arg ref="systemFaultFactory"/>
</bean>
</list>
</property>
</bean>
<!-- aspect for handling unchecked endpoint exceptions -->
<bean id="handleUncheckedEndpointExceptionAdvice"
class="com.gehcit.cp.ws.infrastructure.aop.advices.HandleUncheckedEndpointExceptionAdvice">
<constructor-arg ref="exceptionFactory"/>
<property name="exceptionSenderService" ref="exceptionSenderService" />
</bean>
<bean id="handleUncheckedEndpointExceptionPointcut"
class="org.springframework.aop.support.annotation.AnnotationMatchingPointcut">
<constructor-arg type="java.lang.Class">
<null/>
</constructor-arg>
<constructor-arg type="java.lang.Class"
value="com.gehcit.cp.ws.infrastructure.aop.annotations.HandleUncheckedEndpointException"/>
</bean>
<bean id="handleUncheckedEndpointExceptionAdvisor"
class="org.springframework.aop.support.DefaultPointcutAdvisor">
<property name="advice" ref="handleUncheckedEndpointExceptionAdvice"/>
<property name="pointcut"
ref="handleUncheckedEndpointExceptionPointcut"/>
</bean>
The bean is being initialized in context-applix.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:amq="http://activemq.apache.org/schema/core"
xmlns:jms="http://www.springframework.org/schema/jms"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://activemq.apache.org/schema/core
http://activemq.apache.org/schema/core/activemq-core.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/jms
http://www.springframework.org/schema/jms/spring-jms.xsd">
<!-- Activemq connection factory start -->
<bean id ="connectionAmqFactory"
class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL"
value="vm://broker#{T(com.gehcit.cp.ws.ServiceProperties).instance().getProperty(T(com.gehcit.cp.Constants).CENTRICITY_DEPLOY_ID)}-applix"
/>
</bean>
<!-- A POJO that implements the JMS message listener -->
<bean id="aplixSubscriberQueueService"
class="com.gehcit.cp.cem.aplix.jms.listener.AplixSubscriberQueueListener"
/>
<bean id="exceptionSenderService"
class="com.gehcit.cp.cem.aplix.jms.service.Impl.AplixPublisherQueueServiceImpl"
/>
<!-- A destination in ActiveMQ -->
<!--amq:topic id="destination" physicalName="APLIX.ERRORINFO" /-->
<!-- A destination in ActiveMQ -->
<amq:queue id="destination" physicalName="APLIX.ERRORINFO" />
<!-- A destination in ActiveMQ end-->
<!-- A cached connection to wrap the ActiveMQ connection -->
<bean id="cachedAmqConnectionFactory"
class="org.springframework.jms.connection.CachingConnectionFactory"
p:targetConnectionFactory-ref="connectionAmqFactory"
p:sessionCacheSize="10" />
<!-- Adding JMS transaction Manager -->
<bean id="TransactionManager"
class="org.springframework.jms.connection.JmsTransactionManager">
<property name="connectionFactory" ref="cachedAmqConnectionFactory"/>
</bean>
<!-- Adding JMS transaction Manager -End -->
<!-- A JmsTemplate instance that uses the connection and destination -->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate"
p:connectionFactory-ref="cachedAmqConnectionFactory"
p:defaultDestination-ref="destination" />
<!-- A JmsTemplate instance that uses the connection and destination end -->
<!--Cofiguring JMS container and listener-->
<jms:listener-container container-type="default"
connection-factory="cachedAmqConnectionFactory" destination-type="queue" >
<jms:listener destination="APLIX.ERRORINFO"
ref="aplixSubscriberQueueService" method="onMessage" />
</jms:listener-container>
<!--Cofiguring JMS container and listener end-->
<!-- The Spring message listener container configuration -->
<amq:broker start="true" persistent="false"
brokerName="broker#{T(com.gehcit.cp.ws.ServiceProperties).instance().getProperty(T(com.gehcit.cp.Constants).CENTRICITY_DEPLOY_ID)}-applix"
deleteAllMessagesOnStartup="false" >
<amq:managementContext>
<amq:managementContext createConnector="false"/>
</amq:managementContext>
<amq:systemUsage>
<amq:systemUsage>
<amq:memoryUsage>
<amq:memoryUsage limit="512 mb"/>
</amq:memoryUsage>
<amq:tempUsage>
<amq:tempUsage limit="2 gb"/>
</amq:tempUsage>
</amq:systemUsage>
</amq:systemUsage>
<amq:transportConnectors>
<amq:transportConnector name="vm"
uri="vm://broker#{T(com.gehcit.cp.ws.ServiceProperties).instance().getProperty(T(com.gehcit.cp.Constants).CENTRICITY_DEPLOY_ID)}-applix"/>
</amq:transportConnectors>
</amq:broker>
</beans>
Can someone help me find a way to refer beans from other xml files in Spring 5.2.x.
Note: We have changed the classloading part with Spring 5.2.
Added this to the web.xml
<listener-class>com.gehcit.cp.ws.infrastructure.security.BeanFactoryContextLoaderListener</listener-class>
</listener>
<!-- <context-param>
<param-name>locatorFactorySelector</param-name>
<param-value>/beanRefFactory.xml</param-value>
</context-param> -->
BeanFactoryContextLoaderListener.java
package com.gehcit.cp.ws.infrastructure.security;
import javax.servlet.ServletContext;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.ContextLoaderListener;
public class BeanFactoryContextLoaderListener extends ContextLoaderListener {
private static Logger log = Logger.getLogger(BeanFactoryContextLoaderListener.class)
#Override
protected ApplicationContext loadParentContext(ServletContext servletContext) {
log.info("Entered loadParentContext");
ApplicationContext ctx = new ClassPathXmlApplicationContext("beanRefFactory.xml");
log.info("Exit loadParentContext" + ctx.toString());
return ctx;
}
}
This has something to do with ApplicationContext which I am unable to resolve.
Related
This example is working fine in Tomcat9 with same jar but not working in Resin 4.0.61 Web server
Configuration for Spring MVC in resin.xml file -
<servlet>
<servlet-name>springportfolio</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springportfolio-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup></servlet>
<servlet-mapping>
<servlet-name>springportfolio</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
springportfolio-servlet.xml configuration file-
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Add support for conversion, formatting and validation support -->
<mvc:annotation-driven />
<!-- Add support for component scanning -->
<context:component-scan
base-package="com.example.portfolio" />
<!-- Define Spring MVC view resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix"
value="/web-inf/views/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Step 1: Define Database DataSource / connection pool -->
<bean id="myDataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass"
value="oracle.jdbc.driver.OracleDriver" />
<property name="jdbcUrl"
value="xxxxxx" />
<property name="user" value="xxxx" />
<property name="password" value="xxx" />
<!-- these are connection pool properties for C3P0 -->
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="maxIdleTime" value="30000" />
</bean>
<!-- Step 2: Setup Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan"
value="com.example.portfolio.entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle12cDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- Step 3: Setup Hibernate transaction manager -->
<bean id="myTransactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- Step 4: Enable configuration of transactional behavior based on annotations -->
<tx:annotation-driven
transaction-manager="myTransactionManager" />
Getting Exception - ERROR | Context initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'customerController': Unsatisfied
dependency expressed through field 'userService'; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'userServiceImp': Unsatisfied dependency
expressed through field 'userDao'; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'customerDAOImpl': Unsatisfied
dependency expressed through field 'sessionFactory'; nested exception
is org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'sessionFactory' defined in ServletContext
resource [/WEB-INF/springportfolio-servlet.xml]: Invocation of init
method failed; nested exception is java.lang.NoSuchMethodError:
javax.persistence.Table.indexes()[Ljavax/persistence/Index;
Resin 4.0.61 conforms to JEE 6.0 specification. The JEE 6.0 includes JPA in version 2.0. According to the error message a JPA in version 2.1 is expected by the application. Either downgrade the application to JPA 2.0 or upgrade the server to JPA 2.1 as described in this forum
I am facing a null pointer exception on my app , I am annotating Dao with #Repository , the servive by #Service , controller with #Controller and service inside it with #ManagedProperty, I am suspecting my application context is not well configured so here there is:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xml:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<!-- Enable Spring Annotation Configuration -->
<context:annotation-config/>
<!-- Scan for all of Spring components such as Spring Service -->
<context:component-scan base-package="com.domain.nameOfapp.*" />
<!-- Necessary to get the entity manager injected into the factory bean -->
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<!-- Define Hibernate JPA Vendor Adapter -->
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="org.hibernate.dialect.Oracle10gDialect" />
</bean>
<!-- Entity Manager Factory -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="jpa-persistence" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<property name="packagesToScan">
<list>
<value>com.domain.nameOfapp.*</value>
</list>
</property>
</bean>
<!-- Transaction Manager -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- Detect #Transactional -->
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
Any help would be great! thanks
Your component scan needs to be as below,
<context:component-scan base-package="com.domain.nameOfapp" />
This will scan all the classes under this package including any sub-packages.
Also using #ManagedProperty, are you trying to autowire the spring service bean? I believe you should be using #Autowired.
I have referred to the question asked at Hibernate using multiple databases. My problem is similar but I am facing a different problem.I created two xml file each has a separate datasource and session factory.
In my web.xml I have
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>*The xml files* </param-value>
Once I run the project,the various loadings and the bindings are done from both the xml files.The various annotations and databases/tables are properly identified.But just after this is done before the control even goes outside.I get the following error.
main ERROR [org.springframework.web.context.ContextLoader] - Context initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'daoEager' defined in URL [jar:file:/C:/Users/.../.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/infobutton-service/WEB-INF/lib/core-data-1.0.0-SNAPSHOT.jar!/.../DaoHibernateEagerImpl.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [org.hibernate.SessionFactory]: : No unique bean of type [org.hibernate.SessionFactory] is defined: expected single matching bean but found 2: [sessionFactory, profilesessionFactory]; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [org.hibernate.SessionFactory] is defined: expected single matching bean but found 2: [sessionFactory, profilesessionFactory]
The class DaoHibernateEagerImpl is
#Implementation
#Repository("daoEager")
public class DaoHibernateEagerImpl extends DaoHibernateImpl
{
// ========================= CONSTANTS =================================
/**
* A logger that helps identify this class' printouts.
*/
private static final Logger log = getLogger(DaoHibernateEagerImpl.class);
// ========================= CONSTRUCTORS ==============================
/**
* Required for a Spring DAO bean.
*
* #param sessionFactory
* Hibernate session factory
*/
#Autowired
public DaoHibernateEagerImpl(final SessionFactory sessionFactory)
{
super(sessionFactory);
}
// ========================= DEPENDENCIES ==============================
// ========================= IMPLEMENTATION: Dao =======================
// ========================= IMPLEMENTATION: SearchEngine ==============
}
One of the xml files is
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
<context:annotation-config />
<!--
Data source: reads a properties file and injects them into a DBCP DS
Second datasource for Resource Profiles
-->
<bean id="profiledataSource"
class=".....ConfigurableBasicDataSource">
<constructor-arg index="0">
<bean class="org.apache.commons.dbcp.BasicDataSource" />
</constructor-arg>
<property name="properties">
<bean
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>WEB-INF/datasource-local.properties
</value>
</list>
</property>
</bean>
</property>
<!-- FUR-946: idle connections break. Adding connection testing. -->
<property name="testOnBorrow" value="true" />
<property name="testWhileIdle" value="true" />
</bean>
<!-- Session factory -->
<!-- Session Factory for the second datasource-->
<bean id="profilesessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="profiledataSource" />
<!--
Hibernate configuration properties (read from a properties file)
-->
<property name="hibernateProperties">
<bean
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>WEB-INF/hibernate.properties
</value>
<value>WEB-INF/datasource-local.properties
</value>
</list>
</property>
</bean>
</property>
<!-- Using improved naming strategy -->
<property name="namingStrategy">
<bean class="org.hibernate.cfg.DefaultNamingStrategy" />
</property>
<!-- Mapping annotated classes using search patterns -->
<property name="annotatedClasses">
<list>
<value><![CDATA[....profiledb.domain.Profiles]]></value>
</list>
</property>
</bean>
<!-- Hibernate data access template -->
<bean id="profilehibernateTemplate"
class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="profilesessionFactory" />
</bean>
<tx:annotation-driven />
<!-- a PlatformTransactionManager is still required -->
<bean id="profiletransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="profilesessionFactory" />
</bean>
<bean id="profilesdbDao" class="....profiledb.service.ProfilesDaoImpl" >
<property name="sessionFactory" ref="profilesessionFactory"></property>
<context:component-scan base-package="....core.data" />
The other xml file is similar but has a different datasource and the session factory is
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
.....
The error message is pretty clear:
expected single matching bean but found 2: [sessionFactory, profilesessionFactory]
Which is understandable:
<bean id="profilesessionFactory"
<!-- ... -->
<bean id="sessionFactory"
The fix should be simple:
#Autowired
public DaoHibernateEagerImpl(
#Qualifier("profilesessionFactory") final SessionFactory sessionFactory)
If you cannot modify DaoHibernateEagerImpl class, you can always fall-back to XML-based configuration. First disable CLASSPATH scanning of DaoHibernateEagerImpl so that #Autowired is not picked up. Then simply write:
<bean class="DaoHibernateEagerImpl">
<constructor-arg ref="profilesessionFactory"/>
<!-- ... -->
</bean>
Finally you can take advantage of #Primary annotation / primary="true" directive:
<bean id="sessionFactory" primary="true">
<!-- ... -->
This will prefer sessionFactory when autowiring and there are two possibilities instead of throwing an exception.
Its because of...if you dont mention #Primary(annotation) / primary="true"(in xml config), Hiibernate does not know which sessionfactory to pick up.In that case it will give you the error mentioned. Just try with #Primary annotation it will work...
I have an application based on Spring and hibernate.
My task is to create two connectors in this application to database - one connector is only to READ and second is to READ, WRITE etc.
How my configuration should looks like.
Now in WEB-INF folder i have 3 files:
hibernate-context:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<context:property-placeholder location="/WEB-INF/spring.properties" />
<!-- Enable annotation style of managing transactions -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- Declare the Hibernate SessionFactory for retrieving Hibernate sessions -->
<!-- See http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/orm/hibernate3/annotation/AnnotationSessionFactoryBean.html -->
<!-- See http://docs.jboss.org/hibernate/stable/core/api/index.html?org/hibernate/SessionFactory.html -->
<!-- See http://docs.jboss.org/hibernate/stable/core/api/index.html?org/hibernate/Session.html -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
p:dataSource-ref="dataSource"
p:configLocation="${hibernate.config}"
p:packagesToScan="com.esb.scs"/>
<!-- Declare a datasource that has pooling capabilities-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close"
p:driverClass="${app.jdbc.driverClassName}"
p:jdbcUrl="${app.jdbc.url}"
p:user="${app.jdbc.username}"
p:password="${app.jdbc.password}"
p:acquireIncrement="5"
p:idleConnectionTestPeriod="60"
p:maxPoolSize="100"
p:maxStatements="50"
p:minPoolSize="10" />
<!-- Declare a transaction manager-->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" />
</beans>
hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
</session-factory>
</hibernate-configuration>
spring.properties:
# database properties
app.jdbc.driverClassName=com.mysql.jdbc.Driver
app.jdbc.url=jdbc:mysql://localhost/database
app.jdbc.username=user
app.jdbc.password=password
#hibernate properties
hibernate.config=/WEB-INF/hibernate.cfg.xml
how can i create two connections to database in one application?
My question is becouse i have two databases with replication, where one is only for read and the secound is for write...
With your help i've created file like this:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<context:property-placeholder location="/WEB-INF/spring.properties" />
<!-- Enable annotation style of managing transactions -->
<tx:annotation-driven transaction-manager="transactionManager" />
<tx:annotation-driven transaction-manager="transactionManagerr" />
<!-- Declare the Hibernate SessionFactory for retrieving Hibernate sessions -->
<!-- See http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/orm/hibernate3/annotation/AnnotationSessionFactoryBean.html -->
<!-- See http://docs.jboss.org/hibernate/stable/core/api/index.html?org/hibernate/SessionFactory.html -->
<!-- See http://docs.jboss.org/hibernate/stable/core/api/index.html?org/hibernate/Session.html -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
p:dataSource-ref="dataSource"
p:configLocation="${hibernate.config}"
p:packagesToScan="com.esb.scs"/>
<!-- Declare a datasource that has pooling capabilities-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close"
p:driverClass="${app.jdbc.driverClassName}"
p:jdbcUrl="${app.jdbc.url}"
p:user="${app.jdbc.username}"
p:password="${app.jdbc.password}"
p:acquireIncrement="5"
p:idleConnectionTestPeriod="60"
p:maxPoolSize="100"
p:maxStatements="50"
p:minPoolSize="10" />
<!-- Declare a transaction manager-->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" />
<bean id="sessionFactoryr" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
p:dataSource-ref="dataSourcer"
p:configLocation="${hibernate.config}"
p:packagesToScan="com.esb.scs"/>
<!-- Declare a datasource that has pooling capabilities-->
<bean id="dataSourcer" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close"
p:driverClass="${app.jdbc.driverClassName}"
p:jdbcUrl="${app.jdbc.url}"
p:user="${appr.jdbc.username}"
p:password="${appr.jdbc.password}"
p:acquireIncrement="5"
p:idleConnectionTestPeriod="60"
p:maxPoolSize="100"
p:maxStatements="50"
p:minPoolSize="10" />
<!-- Declare a transaction manager-->
<bean id="transactionManagerr" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactoryr" />
</beans>
and now when i have in service :
#Resource(name="sessionFactory")
private SessionFactory sessionFactory;
#Resource(name="sessionFactoryr")
private SessionFactory sessionFactoryr;
and when i trying to make query with sessionFactoryr
i get Error:
No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
but i have
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
in web.xml
To set up two transaction managers, just declare them in your app context, I use a properties file and read in connection details. I set what type of access hibernate has in that prop file (and also restrict permissions on the db server) :
<bean id="sessionFactoryOne"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
p:dataSource-ref="dataSource" p:configLocation="WEB-INF/classes/hibernate.cfg.xml"
p:packagesToScan="com.mycompany" />
<bean id="dataSourceONE" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close" p:driverClass="${app.jdbc.driverClassName}"
p:jdbcUrl="${app.jdbc.url}" p:user="${app.jdbc.username}" p:password="${app.jdbc.password}"
p:acquireIncrement="5" p:idleConnectionTestPeriod="60" p:maxPoolSize="10"
p:maxStatements="50" p:minPoolSize="10" />
<!-- Declare a transaction manager-->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory">
<bean id="sessionFactoryTWO" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
p:dataSource-ref="dataSourceTWO"
p:configLocation="WEB-INF/classes/hibernateTWO.cfg.xml"
p:packagesToScan="com.mycompany"/>
<!-- Declare a datasource that has pooling capabilities-->
<bean id="dataSourceTWO" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close"
p:driverClass="${two.jdbc.driverClassName}"
p:jdbcUrl="${two.jdbc.url}"
p:user="${two.jdbc.username}"
p:password="${two.jdbc.password}"
p:acquireIncrement="2"
p:idleConnectionTestPeriod="60"
p:maxPoolSize="5"
p:maxStatements="50"
p:minPoolSize="1" />
<!-- Declare a second transaction manager-->
<bean id="transactionManagerTWO" class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactoryTWO">
<qualifier value="Traveller"/>
and then you can reference them like in yr service layer like so :
#Resource(name = "sessionFactoryTWO")
private SessionFactory sessionFactoryTWO;
#Resource(name = "sessionFactory")
private SessionFactory sessionFactory;
then for methods in your service layer you will have to make methods transactional :
#Transactional(readOnly = true)
public void myReadOnlyMethod(Whatever whatever)
#Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void myWriteMethod(Whatever whatever)
I want to create my wsdl by spring-ws automatically and I inserted the code below to my app context file, but I got the error;
"Cannot locate BeanDefinitionParser for element [dynamic-wsdl]"
what does that mean and what can I do? tnx
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:sws="http://www.springframework.org/schema/web-services"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org /schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/web-services http://www.springframework.org/schema/web-services/web-services-2.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="payloadMapping"
class="org.springframework.ws.server.endpoint.mapping.PayloadRootQNameEndpointMapping">
<property name="defaultEndpoint" ref="inferenceEndPoint" />
<property name="interceptors">
<list>
<ref local="validatingInterceptor" />
<ref local="payLoadInterceptor" />
</list>
</property>
</bean>
<bean id="payLoadInterceptor"
class="org.springframework.ws.server.endpoint.interceptor.PayloadLoggingInterceptor" />
<bean id="validatingInterceptor"
class="org.springframework.ws.soap.server.endpoint.interceptor.PayloadValidatingInterceptor">
<description>
This interceptor validates the incoming
message contents
according to the 'Request.xsd' XML
Schema file.
</description>
<property name="schema" value="/WEB-INF/schemas/Request.xsd" />
<property name="validateRequest" value="true" />
<property name="validateResponse" value="false" />
</bean>
<bean id="inferenceEndPoint" class="com.mywebsite.ws.web.InferenceEndPoint">
<property name="messageService" ref="messageService" />
</bean>
<bean id="messageService" class="com.mywebsite.ws.service.MessageService">
<property name="inferenceService" ref="inferenceService" />
</bean>
<bean id="schema" class="org.springframework.xml.xsd.SimpleXsdSchema">
<property name="xsd" value="/WEB-INF/schemas/Request.xsd" />
</bean>
<sws:dynamic-wsdl id="mtwsdl"
portTypeName="mtWS"
locationUri="http://localhost:8080/mws/">
<sws:xsd location="/WEB-INF/schemas/Request.xsd" />
</sws:dynamic-wsdl>
<bean id="inferenceService" class="com.mywebsite.ws.im.InferenceService">
<property name="webServiceConfiguration" ref="playerConfiguration" />
</bean>
<!-- <bean id="inferenceConfig" class="com.mywebsite.ws.im.InferenceService">
<constructor-arg ref="playerConfiguration"/> </bean> -->
<!-- ~~~~~~~ Application beans ~~~~~~~ -->
<bean id="playerConfiguration"
class="com.mywebsite.ws.configuration.WebServiceConfiguration"
init-method="init">
<property name="playerConfigXml" value="/WEB-INF/config/webserviceconfiguration.xml" />
<property name="executingPathResource" value="/WEB-INF" />
<property name="developmentMode" value="true" />
</bean>
Replace the first section of your appcontext where you define namespaces:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:sws="http://www.springframework.org/schema/web-services"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/web-services http://www.springframework.org/schema/web-services/web-services-2.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
I highly suggest to use Maven. The error you are getting is due to a missing library. In Maven you should have an entry like the following.
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-core</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
I suggest you look at the class path and also server run time path, I think you may have both (spring-ws 1.5.x and spring-ws 2.x) version's of jar files either in the compile/run time path. If that is not the case clean up the both class and run time path and add only spring-ws 2.x jar files.
As for the differences, when spring framework name space handler (WebServicesNamespaceHandler) encounters (dynamic-wsdl tag in spring context file), It will register a (DynamicWsdlBeanDefinitionParser) bean with all the properties specified in the dynamic wsdl tag. It is essentially same as you registering (DefaultWsdl11Definition) bean in spring context.