JPA 2.0 & Hibernate 4.0.1 & Spring 3.1.1 Compatibility - java

I am using Spring 3.1.1 in my application.
I have integrated JPA and Hibernate 4.0.1 into it.
My entityManagerFactory and few more beans are not getting instantiated.
java.lang.NoSuchMethodError: org.hibernate.cfg.Environment.verifyProperties(Ljava/util/Map;)V
at org.hibernate.service.ServiceRegistryBuilder.buildServiceRegistry(ServiceRegistryBuilder.java:244)
at org.hibernate.ejb.Ejb3Configuration.buildLifecycleControledServiceRegistry(Ejb3Configuration.java:930)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:903)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:889)
at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:73)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:268)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:310)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
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:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:400)
at org.springframework.beans.factory.BeanFactoryUtils.beansOfTypeIncludingAncestors(BeanFactoryUtils.java:275)
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:70)
at org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor.setBeanFactory(PersistenceExceptionTranslationPostProcessor.java:103)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeAwareMethods(AbstractAutowireCapableBeanFactory.java:1475)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1443)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
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:197)
at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:728)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:449)
at org.mule.config.spring.SpringRegistry.doInitialise(SpringRegistry.java:89)
at org.mule.registry.AbstractRegistry.initialise(AbstractRegistry.java:109)
at org.mule.config.spring.SpringXmlConfigurationBuilder.createSpringRegistry(SpringXmlConfigurationBuilder.java:116)
at org.mule.config.spring.SpringXmlConfigurationBuilder.doConfigure(SpringXmlConfigurationBuilder.java:73)
at org.mule.config.builders.AbstractConfigurationBuilder.configure(AbstractConfigurationBuilder.java:46)
at org.mule.config.builders.AbstractResourceConfigurationBuilder.configure(AbstractResourceConfigurationBuilder.java:78)
at org.mule.config.builders.AutoConfigurationBuilder.autoConfigure(AutoConfigurationBuilder.java:101)
at org.mule.config.builders.AutoConfigurationBuilder.doConfigure(AutoConfigurationBuilder.java:57)
at org.mule.config.builders.AbstractConfigurationBuilder.configure(AbstractConfigurationBuilder.java:46)
at org.mule.config.builders.AbstractResourceConfigurationBuilder.configure(AbstractResourceConfigurationBuilder.java:78)
at org.mule.context.DefaultMuleContextFactory.createMuleContext(DefaultMuleContextFactory.java:80)
at org.mule.module.launcher.application.DefaultMuleApplication.init(DefaultMuleApplication.java:208)
at org.mule.module.launcher.application.ApplicationWrapper.init(ApplicationWrapper.java:64)
at org.mule.module.launcher.DefaultMuleDeployer.deploy(DefaultMuleDeployer.java:46)
at org.mule.tooling.server.application.ApplicationDeployer.run(ApplicationDeployer.java:56)
at org.mule.tooling.server.application.ApplicationDeployer.main(ApplicationDeployer.java:88)
Exception in thread "main" org.mule.module.launcher.DeploymentInitException: NoSuchMethodError: org.hibernate.cfg.Environment.verifyProperties(Ljava/util/Map;)V
at org.mule.module.launcher.application.DefaultMuleApplication.init(DefaultMuleApplication.java:220)
at org.mule.module.launcher.application.ApplicationWrapper.init(ApplicationWrapper.java:64)
at org.mule.module.launcher.DefaultMuleDeployer.deploy(DefaultMuleDeployer.java:46)
at org.mule.tooling.server.application.ApplicationDeployer.run(ApplicationDeployer.java:56)
at org.mule.tooling.server.application.ApplicationDeployer.main(ApplicationDeployer.java:88)
Caused by: org.mule.api.config.ConfigurationException: Error creating bean with name 'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0' defined in URL [file:/C:/Users/User-1/MuleStudio/workspace/.mule/apps/eigSourceCode/appendContext.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in URL [file:/C:/Users/User-1/MuleStudio/workspace/.mule/apps/eigSourceCode/appendContext.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.hibernate.cfg.Environment.verifyProperties(Ljava/util/Map;)V (org.mule.api.lifecycle.InitialisationException) (org.mule.api.config.ConfigurationException)
at org.mule.config.builders.AbstractConfigurationBuilder.configure(AbstractConfigurationBuilder.java:52)
at org.mule.config.builders.AbstractResourceConfigurationBuilder.configure(AbstractResourceConfigurationBuilder.java:78)
at org.mule.context.DefaultMuleContextFactory.createMuleContext(DefaultMuleContextFactory.java:80)
at org.mule.module.launcher.application.DefaultMuleApplication.init(DefaultMuleApplication.java:208)
... 4 more
Caused by: org.mule.api.config.ConfigurationException: Error creating bean with name 'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0' defined in URL [file:/C:/Users/User-1/MuleStudio/workspace/.mule/apps/eigSourceCode/appendContext.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in URL [file:/C:/Users/User-1/MuleStudio/workspace/.mule/apps/eigSourceCode/appendContext.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.hibernate.cfg.Environment.verifyProperties(Ljava/util/Map;)V (org.mule.api.lifecycle.InitialisationException)
at org.mule.config.builders.AbstractConfigurationBuilder.configure(AbstractConfigurationBuilder.java:52)
at org.mule.config.builders.AbstractResourceConfigurationBuilder.configure(AbstractResourceConfigurationBuilder.java:78)
at org.mule.config.builders.AutoConfigurationBuilder.autoConfigure(AutoConfigurationBuilder.java:101)
at org.mule.config.builders.AutoConfigurationBuilder.doConfigure(AutoConfigurationBuilder.java:57)
at org.mule.config.builders.AbstractConfigurationBuilder.configure(AbstractConfigurationBuilder.java:46)
... 7 more
Caused by: org.mule.api.lifecycle.InitialisationException: Error creating bean with name 'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0' defined in URL [file:/C:/Users/User-1/MuleStudio/workspace/.mule/apps/eigSourceCode/appendContext.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in URL [file:/C:/Users/User-1/MuleStudio/workspace/.mule/apps/eigSourceCode/appendContext.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.hibernate.cfg.Environment.verifyProperties(Ljava/util/Map;)V
at org.mule.registry.AbstractRegistry.initialise(AbstractRegistry.java:117)
at org.mule.config.spring.SpringXmlConfigurationBuilder.createSpringRegistry(SpringXmlConfigurationBuilder.java:116)
at org.mule.config.spring.SpringXmlConfigurationBuilder.doConfigure(SpringXmlConfigurationBuilder.java:73)
at org.mule.config.builders.AbstractConfigurationBuilder.configure(AbstractConfigurationBuilder.java:46)
... 11 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0' defined in URL [file:/C:/Users/User-1/MuleStudio/workspace/.mule/apps/eigSourceCode/appendContext.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in URL [file:/C:/Users/User-1/MuleStudio/workspace/.mule/apps/eigSourceCode/appendContext.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.hibernate.cfg.Environment.verifyProperties(Ljava/util/Map;)V
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
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:197)
at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:728)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:449)
at org.mule.config.spring.SpringRegistry.doInitialise(SpringRegistry.java:89)
at org.mule.registry.AbstractRegistry.initialise(AbstractRegistry.java:109)
... 14 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in URL [file:/C:/Users/User-1/MuleStudio/workspace/.mule/apps/eigSourceCode/appendContext.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.hibernate.cfg.Environment.verifyProperties(Ljava/util/Map;)V
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1455)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
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:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:400)
at org.springframework.beans.factory.BeanFactoryUtils.beansOfTypeIncludingAncestors(BeanFactoryUtils.java:275)
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:70)
at org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor.setBeanFactory(PersistenceExceptionTranslationPostProcessor.java:103)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeAwareMethods(AbstractAutowireCapableBeanFactory.java:1475)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1443)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
... 23 more
Caused by: java.lang.NoSuchMethodError: org.hibernate.cfg.Environment.verifyProperties(Ljava/util/Map;)V
at org.hibernate.service.ServiceRegistryBuilder.buildServiceRegistry(ServiceRegistryBuilder.java:244)
at org.hibernate.ejb.Ejb3Configuration.buildLifecycleControledServiceRegistry(Ejb3Configuration.java:930)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:903)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:889)
at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:73)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:268)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:310)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452)
... 38 more
I am not supposed to use Maven, so i am adding jars directly to class path.
The Jars inside class path are:
My persistance.xml is inside META-INF, and the code inside is:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="03offileLogger">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.comviva.mfs.eig.persistance.jpa.entities.TransactionLog</class>
</persistence-unit>
</persistence>
The appendContext.xml is my application Context file used for configuring spring beans which contains the following code:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<!-- scans the classpath for annotated components (including #Repostory
and #Service that will be auto-registered as Spring beans -->
<context:component-scan
base-package="com.comviva.mfs.eig.logging.dataAccess, com.comviva.mfs.eig.logging.service" />
<!-- methods or classes needing to run in a complete transaction will be
annotated with Transactional -->
<tx:annotation-driven />
<bean
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/eigDB" />
<property name="username" value="root" />
<property name="password" value="tiger" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="03offileLogger" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
</bean>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
</beans>
The errors pasted above are cut to fit the size,
But after each error it is saying
Invocation of init method failed;
Initialization of bean failed;
I read it somewhere that there is some version conflict, so the entityManagerFactory is not being instantiated.
Update:
The code below shows my entity (only one table).
package com.comviva.mfs.eig.persistance.jpa.entities;
import java.io.Serializable;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* The persistent class for the transaction_logs database table.
*
*/
#Entity
#Table(name="transaction_logs")
public class TransactionLog implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="TRANSACTION_ID")
private Long transaction_id;
#Column(name="INTERFACE_ID")
private String interfaceId;
#Column(name="FROM_ACCOUNT")
private String from_account;
#Column(name="SERVICE_TYPE")
private String serviceType;
#Column(name = "MSISDN")
private String msisdn;
#Column(name="TRANSACTION_TIME")
private Timestamp transactionTime;
#Column(name = "TRANSACTION_DATE")
private Timestamp transactionDate;
#Column(name="FROM_ACCOUNT_TYPE")
private Integer fromAccountType;
#Column(name="TRANSMISSION_DATE_TIME")
private Timestamp transmissionDateTime;
#Column(name="INTERFACE_TXN_ID")
private Long interfaceTxnId;
#Column(name="AVILABLE_BALANCE")
private Double avilableBalance;
#Column(name="TOTAL_BALANCE")
private Double totalBalance;
#Column(name="TXN_STATUS")
private String txnStatus;
#Column(name="MESSAGE")
private String message;
public TransactionLog() {
}
public Long getTransaction_id() {
return transaction_id;
}
public void setTransaction_id(Long transaction_id) {
this.transaction_id = transaction_id;
}
public String getInterfaceId() {
return interfaceId;
}
public void setInterfaceId(String interfaceId) {
this.interfaceId = interfaceId;
}
public String getFrom_account() {
return from_account;
}
public void setFrom_account(String from_account) {
this.from_account = from_account;
}
public String getServiceType() {
return serviceType;
}
public void setServiceType(String serviceType) {
this.serviceType = serviceType;
}
public String getMsisdn() {
return msisdn;
}
public void setMsisdn(String msisdn) {
this.msisdn = msisdn;
}
public Timestamp getTransactionTime() {
return transactionTime;
}
public void setTransactionTime(Timestamp transactionTime) {
this.transactionTime = transactionTime;
}
public Timestamp getTransactionDate() {
return transactionDate;
}
public void setTransactionDate(Timestamp transactionDate) {
this.transactionDate = transactionDate;
}
public Integer getFromAccountType() {
return fromAccountType;
}
public void setFromAccountType(Integer fromAccountType) {
this.fromAccountType = fromAccountType;
}
public Timestamp getTransmissionDateTime() {
return transmissionDateTime;
}
public void setTransmissionDateTime(Timestamp transmissionDateTime) {
this.transmissionDateTime = transmissionDateTime;
}
public Long getInterfaceTxnId() {
return interfaceTxnId;
}
public void setInterfaceTxnId(Long interfaceTxnId) {
this.interfaceTxnId = interfaceTxnId;
}
public Double getAvilableBalance() {
return avilableBalance;
}
public void setAvilableBalance(Double avilableBalance) {
this.avilableBalance = avilableBalance;
}
public Double getTotalBalance() {
return totalBalance;
}
public void setTotalBalance(Double totalBalance) {
this.totalBalance = totalBalance;
}
public String getTxnStatus() {
return txnStatus;
}
public void setTxnStatus(String txnStatus) {
this.txnStatus = txnStatus;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
Please help me Resolve my Problem.

The error message 'java.lang.NoSuchMethodError: org.hibernate.cfg.Environment.verifyProperties" means you do have a different version of class org.hibernate.cfg.Environment
Your error log says you are using mule. Mule comes with its own hibernate jar. Please check the lib directory of mule to confirm that you don't have a conflicting hibernate jars.

Do you have any Entities, relationships defined? Can you take thise out and let just EntityManager initialize?
The reason is simple, I think I saw this kind of errors when there was a problem with my Entities and relations

Replace the Hibernate jars present in the Mule server,
i.e:location sample: C:\dev\AnypointStudio\plugins\org.mule.tooling.server.3.5.2.ee_4.1.0.201410031231\mule\lib\opt.
Reason: If you have developed your app with specific version of Hibernate, then you need to have the same version in the mule server because while you running your app in the mule server it uses its own copy of it.

Related

Error creating bean with name. Combine bean validation and Spring-based validation

I want combine bean validation and Spring validation (based on the book "Spring MVC Beginner's Guide"), but there is errors:
My logs:
2017-03-04 19:09:54 ERROR DispatcherServlet:502 - Context initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'productController': Unsatisfied dependency expressed through field 'productValidator'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'productValidator': Unsatisfied dependency expressed through field 'beanValidator'; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'javax.validation.Validator' available: expected single matching bean but found 2: org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean#0,validator
at [...]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'productValidator': Unsatisfied dependency expressed through field 'beanValidator'; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'javax.validation.Validator' available: expected single matching bean but found 2: org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean#0,validator
at [...]
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'javax.validation.Validator' available: expected single matching bean but found 2: org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean#0,validator
at [...]
My controller:
#Controller()
#RequestMapping("/products")
public class ProductController {
#Autowired
private ProductService productService;
#Autowired
private ProductValidator productValidator;
[...]
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String processAddNewProductForm(#Valid #ModelAttribute("newProduct") Product productToBeAdded, BindingResult result,
HttpServletRequest httpServletRequest){
if(result.hasErrors())
return "addProduct";
String[] suppressedFields = result.getSuppressedFields();
if(suppressedFields.length > 0){
throw new RuntimeException("abc" + StringUtils.arrayToCommaDelimitedString(suppressedFields));
}
MultipartFile productImage = productToBeAdded.getProductImage();
String rootDirectory = httpServletRequest.getSession().getServletContext().getRealPath("/");
if(productImage != null && !productImage.isEmpty()){
try {
productImage.transferTo(new File(rootDirectory + "resources\\images\\" +
productToBeAdded.getProductId() + ".png"));
} catch (IOException e) {
throw new RuntimeException("abcd", e);
}
}
productService.addProduct(productToBeAdded);
return "redirect:/products";
}
#InitBinder
public void initialiseBinder(WebDataBinder binder){
binder.setValidator(productValidator);
}
[...]
}
My class validation
#Component
public class ProductValidator implements Validator {
#Autowired
private javax.validation.Validator beanValidator;
private Set<Validator> springValidators;
public ProductValidator() {
this.springValidators = new HashSet<>();
}
public void setSpringValidators(Set<Validator> springValidators) {
this.springValidators = springValidators;
}
#Override
public boolean supports(Class<?> aClass) {
return Product.class.isAssignableFrom(aClass);
}
#Override
public void validate(Object target, Errors errors) {
Set<ConstraintViolation<Object>> constraintViolations = beanValidator.validate(target);
for(ConstraintViolation<Object> constraintViolation: constraintViolations){
String propertyPath = constraintViolation.getPropertyPath().toString();
String message = constraintViolation.getMessage();
errors.rejectValue(propertyPath, "", message);
}
for(Validator validator: springValidators){
validator.validate(target, errors);
}
}
}
My DispatcherServlet-context
<?xml version="1.0" encoding="UTF-8"?>
[...]
<mvc:annotation-driven enable-matrix-variables="true"/>
<mvc:resources mapping="/resource/**" location="/resources/" />
<mvc:annotation-driven enable-matrix-variables="true" validator="validator"/>
<context:component-scan base-package="com.packt.webstore" />
[...]
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="pl" />
</bean>
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="validationMessageSource" ref="messageSource"/>
</bean>
<bean id="productValidator" class="com.packt.webstore.validator.ProductValidator">
<property name = "springValidators">
<set>
<ref bean = "unitsInStockValidator"/>
</set>
</property>
</bean>
<bean id="unitsInStockValidator" class="com.packt.webstore.validator.UnitsInStockValidator"/>
</beans>
Initially, there wasn't annotation #Component, I added it, but nothing change
The error you are getting is b/c spring cannot determine what validator bean to inject into ProductValidator, just flag it as the primary in your bean configuration file so Spring knows which one to use.
<bean id="validator" primary="true" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="validationMessageSource" ref="messageSource"/>
</bean>

Spring : Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException

First I want to start off saying that I'm a bit new to Spring so the conceptual aspect of it is a bit unclear, and thusly preventing me from understanding the implementation. I'm trying to integrate hibernate and spring together, but I continually get this error.
Error creating bean with name 'facade' defined in class path resource [beans.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'bankDAO' of bean class [data.Facade]: Bean property 'bankDAO' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
org.springframework.beans.factory.BeanCreationException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1396)
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:607)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:925)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:472)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at JUnitTest.HibernateTest.setup(HibernateTest.java:40)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'bankDAO' of bean class [data.Facade]: Bean property 'bankDAO' 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:1064)
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:924)
... 37 more
Here's my BankDAO class
package data;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import beans.Bank;
public class BankDAO {
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public Bank get(int id) {
return (Bank) sessionFactory.getCurrentSession().get(Bank.class, id);
}
#Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public Bank load(int id) {
return (Bank) sessionFactory.getCurrentSession().load(Bank.class, id);
}
}
Façade class
package data;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import beans.*;
import java.util.List;
public class Facade {
private SessionFactory sf = new Configuration().configure().buildSessionFactory();
private static ApplicationContext contxt;
public static void getContext() {
contxt = new ClassPathXmlApplicationContext("beans.xml");
}
public void createAccount(AccountDAO account){
contxt.getBean(AccountDAO.class).insert(account);
System.out.println("Event was inserted");
}
public List<Account> getAllAccounts(){
return contxt.getBean(AccountDAO.class).getAll();
}
}
Beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
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-3.1.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<!-- Use #Transactional instead of <tx:advice> -->
<tx:annotation-driven />
<!-- DataSource bean -->
<bean name="ds" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver" />
<property name="username" value="root" />
<property name="password" value="" />
<property name="url" value="localhost" />
</bean>
<!-- SessionFactory -->
<bean name="sf"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="ds" />
<property name="packagesToScan" value="beans" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.connection.pool_size">20</prop>
<prop key="hibernate.dialect"> org.hibernate.dialect.Oracle10gDialect </prop>
<prop key="show_sql">true</prop>
</props>
</property>
</bean>
<!-- Transaction Manager -->
<bean name="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sf" />
</bean>
<!-- DAO beans -->
<bean name="bankDAO" class="data.BankDAO"> <property name="sessionFactory" ref="sf" /> </bean>
<bean name="accountDAO" class="data.AccountDAO"> <property name="sessionFactory" ref="sf" /> </bean>
</bean>
<!-- Facade bean -->
<bean name="facade" class="dataTier.DataFacade">
<property name="bankDAO" ref="bankDAO" />
<property name="accountDAO" ref="accountDAO" />
</bean>
</beans>
Any help is appreciated thank you.
Error log clearly telling that it is not finding setter for bankDAO
Error creating bean with name 'facade' defined in class path resource
[beans.xml]: Error setting property values; nested exception is
org.springframework.beans.NotWritablePropertyException: Invalid
property 'bankDAO' of bean class [data.Facade]: Bean property
'bankDAO' is not writable or has an invalid setter method. Does the
parameter type of the setter match the return type of the getter?
To fix it, create property bankDAO along with setter/getter as follows:
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import beans.*;
import java.util.List;
public class Facade {
private SessionFactory sf = new Configuration().configure()
.buildSessionFactory();
private static ApplicationContext contxt;
private BankDAO bankDAO;
public static void getContext() {
contxt = new ClassPathXmlApplicationContext("beans.xml");
}
public void createAccount(AccountDAO account) {
contxt.getBean(AccountDAO.class).insert(account);
System.out.println("Event was inserted");
}
public List<Account> getAllAccounts() {
return contxt.getBean(AccountDAO.class).getAll();
}
public BankDAO getBankDAO() {
return bankDAO;
}
public void setBankDAO(BankDAO bankDAO) {
this.bankDAO = bankDAO;
}
}
Also check bean named "facade", as from error logs it seems it should be:
<!-- Facade bean -->
<bean name="facade" class="dataTier.Facade">
<property name="bankDAO" ref="bankDAO" />
<property name="accountDAO" ref="accountDAO" />
</bean>
not
<!-- Facade bean -->
<bean name="facade" class="dataTier.DataFacade">
<property name="bankDAO" ref="bankDAO" />
<property name="accountDAO" ref="accountDAO" />
</bean>

Bean collection Spring: ConversionNotSupportedException

I'm new in Spring and I'm try to create a simple quick start application.
My application is composed by three java classes, the pom.xml file and another xml file:
Produttore.java:
package com.mkyong.core;
import org.springframework.stereotype.Component;
#Component
public class Produttore {
private int iD;
private String ruolo;
public int getiD() {
return iD;
}
public void setiD(int iD) {
this.iD = iD;
}
public String getRuolo() {
return ruolo;
}
public void setRuolo(String ruolo) {
this.ruolo = ruolo;
}
#Override
public String toString(){
return "Produttore " + iD + ", ruolo " + ruolo;
}
}
Team.java:
package com.mkyong.core;
import java.util.List;
import org.springframework.stereotype.Component;
#Component
public class Team {
private Produttore Leader;
private List<Produttore> membri;
public Produttore getLeader() {
return Leader;
}
public void setLeader(Produttore leader) {
Leader = leader;
}
public List<Produttore> getMembri() {
return membri;
}
public void setMembri(List<Produttore> membri) {
this.membri = membri;
}
public void addMembri(Produttore p){
this.membri.add(p);
}
#Override
public String toString(){
return "Trainer " + Leader + " numero membri: " + membri.size();
}
}
test1.java:
package com.mkyong.core;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class test1 {
public static void main(String[] args){
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"Test1xml.xml"});
Team ris=(Team)context.getBean("TeamBean");
System.out.println(ris);
}
}
Test1xml.xml:
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-2.5.xsd">
<bean id="ProduttoreBean" class="com.mkyong.core.Produttore">
<property name="iD" value="1234"/>
<property name="ruolo" value="Trainer"/>
</bean>
<bean id="TeamBean" class="com.mkyong.core.Team">
<property name="Leader">
<bean class="com.mkyong.core.Produttore">
<property name="iD" value="1111"></property>
<property name="ruolo" value="Trainer"/>
</bean>
</property>
<property name="membri">
<util:list list-class="java.util.ArrayList">
<value>0</value>
<ref bean="ProduttoreBean2" />
</util:list>
</property>
</bean>
<bean id="ProduttoreBean2" class="com.mkyong.core.Produttore">
<property name="iD" value="1112" />
<property name="ruolo" value="Junior"/>
</bean>
</beans>
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mkyong.core</groupId>
<artifactId>Spring3Example</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>Spring3Example</name>
<url>http://maven.apache.org</url>
<properties>
<spring.version>3.0.5.RELEASE</spring.version>
</properties>
<dependencies>
<!-- Spring 3 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
</project>
I don't know why, but when I try to lunch the application it fails. I post the error:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'TeamBean' defined in class path resource [Test1xml.xml]: Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.util.ArrayList' to required type 'java.util.List' for property 'membri'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.mkyong.core.Produttore] for property 'membri[0]': no matching editors or conversion strategy found
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
at com.mkyong.core.test1.main(test1.java:8)
Caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.util.ArrayList' to required type 'java.util.List' for property 'membri'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.mkyong.core.Produttore] for property 'membri[0]': no matching editors or conversion strategy found
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:462)
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:499)
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:493)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1371)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1330)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1086)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
... 11 more
Caused by: java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.mkyong.core.Produttore] for property 'membri[0]': no matching editors or conversion strategy found
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:231)
at org.springframework.beans.TypeConverterDelegate.convertToTypedCollection(TypeConverterDelegate.java:520)
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:173)
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:447)
... 17 more
Could someone help me? Thanks a lot
convert value of type [java.lang.String] to required type [com.mkyong.core.Produttore] for property 'membri[0]' : This tells the Spring is unable to convert the String value at first position in arrayList to type Produttore. See the Explanation below :-
private List<Produttore> membri;
The error is because of above line. Because here you are defining that the arraylist with name membri will contain the objects of type Produttore but putting a String value at first position in it in xml i.e. 0:
<util:list list-class="java.util.ArrayList" value- type="com.mkyong.core.Produttore">
*<value>0</value>*
<ref bean="ProduttoreBean2" />
</util:list>
If you convert the decalaration of membri in Team class as below the code will work:
private List<Object> membri;
public List<Object> getMembri() {
return membri;
}
public void setMembri(List<Object> membri) {
this.membri = membri;
}
You should also provide "value-type" property for the list your are defining in your Test1xml.xml.
It should be like this:-
<property name="membri">
<util:list list-class="java.util.ArrayList" value-type="com.mkyong.core.Produttore">
<value>0</value>
<ref bean="ProduttoreBean2" />
</util:list>
</property>

org.springframework.beans.factory.BeanCreationException in spring mvc project

1.I am very new in spring and this question has been asked many times but still i am not able to figure out the wrong things.And getting these exceptions.
This is my console output
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sidSearchController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.jlcindia.spring.mvc.SidValidator com.jlcindia.spring.mvc.SidSearchController.sidValidator; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.web.servlet.handeler.SimpleMappingExceptionResolver] for bean with name 'org.springframework.web.servlet.handeler.SimpleMappingExceptionResolver#0' defined in ServletContext resource [/WEB-INF/jlcindia-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.web.servlet.handeler.SimpleMappingExceptionResolver
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:286)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1055)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:511)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:562)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:871)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:423)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:443)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:459)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:340)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:307)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127)
javax.servlet.GenericServlet.init(GenericServlet.java:212)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581)
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
java.lang.Thread.run(Thread.java:619)
Controller class
#Controller
public class SidSearchController
{
#Autowired
private SidValidator sidValidator;
#RequestMapping(value="/searchStudent",method=RequestMethod.POST)
#ExceptionHandler({StudentNotFoundException.class})
public String searchStudent(#ModelAttribute("sidSearchCommand")SidSearchCommand sidCommand,Errors errors,HttpServletRequest req,Model model){
System.out.println("contact controller");
sidValidator.validate(sidCommand, errors);
if(errors.hasErrors()){
return "sidsearch";
}
String sid=sidCommand.getSid();
String results="";
if(sid.equals("sim-123")||sid.equals("sim-999")) {
StudentTO sto=new StudentTO();
sto.setSid(sid);
sto.setBid("B-99");
sto.setSname("srinivas");
sto.setPhone("99999");
model.addAttribute("STO", sto);
req.setAttribute("STO",sto);
results="sidresults";
}
else
{
req.setAttribute("sidSearchCommand",sidCommand);
throw new StudentNotFoundException(sid);
}return results;
}#RequestMapping(value="/sidsearch")
protected String showSearchPage(Map model) throws ServletException{
System.out.println("show search page");
SidSearchCommand sidCommand=new SidSearchCommand();
model.put("sidSearchCommand", sidCommand);
return "sidsearch";
}
}
3.mvc-dispatcher-servlet.xml:
<context:component-scan base-package="com.jlcindia.spring.mvc" />
<bean id="sidValidator" class="com.jlcindia.spring.mvc.SidValidator"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.InternalResourceView"/>
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
</bean>
<bean class="org.springframework.web.servlet.handeler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="com.jlcindia.spring.mvc.StudentNotFoundException">sidsearch
</prop>
</props>
</property>
</bean>
</beans>
in your mvc-dispatcher-servlet.xml you misspelled the following: org.springframework.web.servlet.handeler.SimpleMappingExceptionResolver
handeler is written instead of handler

Error while connecting to database with spring

First of all this is the first time that I am trying spring. I have a problem while connecting to a database using spring's JDBC template
Here's my code for AddEmployee Servlet:
package com.lftechnology.spring.jdbctemplate.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.lftechnology.spring.jdbctemplate.model.dao.EmployeeDAO;
import com.lftechnology.spring.jdbctemplate.model.dao.EmployeeDAOImpl;
import com.lftechnology.spring.jdbctemplate.model.dao.mysql.EmployeeMySql;
import com.lftechnology.spring.jdbctemplate.model.dto.Employee;
#WebServlet("/AddEmployee")
public class AddEmployee extends HttpServlet
{
private static final long serialVersionUID = 1L;
Employee employee;
public AddEmployee() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
RequestDispatcher dispatcher=request.getRequestDispatcher("addemployee.jsp");
dispatcher.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
EmployeeDAO employeeDAO= (EmployeeDAO) context.getBean("employeeDAO");
employee=new Employee();
String name=(String) request.getAttribute("name");
String designation=(String) request.getAttribute("designation");
employee.setName(name);
employee.setDesignation(designation);
employeeDAO.insert(employee);
RequestDispatcher dispatcher =request.getRequestDispatcher("success.jsp");
dispatcher.forward(request,response);
}
}
Corresponding class named EmployeeMySql for JDBC connection is
package com.lftechnology.spring.jdbctemplate.model.dao.mysql;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import com.lftechnology.spring.jdbctemplate.model.dao.EmployeeDAO;
import com.lftechnology.spring.jdbctemplate.model.dto.Employee;
public class EmployeeMySql extends JdbcTemplate implements EmployeeDAO
{
private DataSource dataSource;
public void setDataSource(DataSource dataSource)
{
System.out.println("Datasource here"+dataSource.toString());
try {
System.out.println("Datasource here"+dataSource.getLoginTimeout());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.dataSource = dataSource;
}
public void insert(Employee employee)
{
String query_sql;
query_sql="INSERT INTO EMPLOYEE (name,designation) VALUES (?,?,?)";
update(query_sql,new Object[]{employee.getName(),employee.getDesignation()});
}
#Override
public Employee retrieveAllData() {
// TODO Auto-generated method stub
return null;
}
}
Similarly my spring bean configuration is spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<bean id="dataSourcee"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/spring" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="employeeDAO" class="com.lftechnology.spring.jdbctemplate.model.dao.mysql.EmployeeMySql">
<property name="dataSource" ref="dataSourcee"/>
</bean>
<!-- import resource="Spring-Datasource.xml" />
<import resource="Spring-Customer.xml" /-->
</beans>
However i always end up with one error which i cant figure out at all.Error that i get is
HTTP Status 500 - Error creating bean with name 'employeeDAO' defined in class path resource [spring.xml]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'dataSource' is required
type Exception report
message Error creating bean with name 'employeeDAO' defined in class path resource [spring.xml]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'dataSource' is required
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeDAO' defined in class path resource [spring.xml]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'dataSource' is required
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1455)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:605)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:925)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:472)
org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
com.lftechnology.spring.jdbctemplate.controller.AddEmployee.doPost(AddEmployee.java:46)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
root cause
java.lang.IllegalArgumentException: Property 'dataSource' is required
org.springframework.jdbc.support.JdbcAccessor.afterPropertiesSet(JdbcAccessor.java:134)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:605)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:925)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:472)
org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
com.lftechnology.spring.jdbctemplate.controller.AddEmployee.doPost(AddEmployee.java:46)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
Could someone tell me what the error really is?
Help would be much appreciated.
In your setDataSource method, make a call to super.setDataSource. You have your own dataSource variable, however, the base class also does some initialization with the given dataSource instance and that is what is missed out.

Categories