Getting an exception while creating simple Spring AOP Throws Advice Demo - java

hi I am getting Exception as ****thread "main" org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException****
while try to make a simple Spring AOP throws advice Demo.
Please some one help me out.
The detail code with exception is mentioned below
MyInterface.java
package com.Spring.Aop.SpringAOPThrowsAdvice;
public class MyImplClass implements MyInterface {
public void m1(){
int java4s = 10/0;
System.out.println("Am in business method..");
}
}
MyInterface.java
package com.Spring.Aop.SpringAOPThrowsAdvice;
public interface MyInterface {
void m1();
}
MyThrowsAdvice.java
package com.Spring.Aop.SpringAOPThrowsAdvice;
import java.lang.reflect.Method;
import org.springframework.aop.ThrowsAdvice;
public class MyThrowsAdvice implements ThrowsAdvice {
//First preference
public void afterThrowing(ArithmeticException e)
{
System.out.println("This is from ArithmeticException method");
}
//Second preference
public void afterThrowing(Method m, Object args[], Object target,Exception e)
{
System.out.println("Am from 4 parameters method called from "+m.getName());
}
//Third preference
public void afterThrowing(Exception e)
{
System.out.println("Fom single parameter method");
}
}
OurLogic.java
package com.Spring.Aop.SpringAOPThrowsAdvice;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class OurLogic {
public static void main(String args[])
{
Resource res = new ClassPathResource("spconfig.xml");
BeanFactory factory = new XmlBeanFactory(res);
MyInterface inter =(MyInterface)factory.getBean("id3");
inter.m1();
}
}
spconfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="id1" class="com.Spring.Aop.SpringAOPThrowsAdvice.MyImplClass" />
<bean id="id2" class="com.Spring.Aop.SpringAOPThrowsAdvice.MyThrowsAdvice" />
<bean id="id3" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces" value="com.Spring.Aop.SpringAOPThrowsAdvice.MyInterface" />
<property name="interceptorNames" >
<list>
<value>id2</value>
</list>
</property>
<property name="target">
<ref bean="id1"/>
</property>
</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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.Spring.Aop</groupId>
<artifactId>SpringAOPThrowsAdvice</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringAOPThrowsAdvice</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>2.5.6</version>
</dependency>
</dependencies>
</project>
Exception is:
May 11, 2017 12:47:38 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spconfig.xml]
Exception in thread "main" org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 2 in XML document from class path resource [spconfig.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 2; columnNumber: 8; cvc-elt.1: Cannot find the declaration of element 'beans'.
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:404)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:342)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:310)
at org.springframework.beans.factory.xml.XmlBeanFactory.<init>(XmlBeanFactory.java:73)
at org.springframework.beans.factory.xml.XmlBeanFactory.<init>(XmlBeanFactory.java:61)
at com.Spring.Aop.SpringAOPThrowsAdvice.OurLogic.main(OurLogic.java:12)
Caused by: org.xml.sax.SAXParseException; lineNumber: 2; columnNumber: 8; cvc-elt.1: Cannot find the declaration of element 'beans'.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:203)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:396)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:327)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:284)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(XMLSchemaValidator.java:1900)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.startElement(XMLSchemaValidator.java:740)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:374)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(XMLNSDocumentScannerImpl.java:613)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:3132)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:852)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:602)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:112)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:505)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:841)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:770)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:243)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:339)
at org.springframework.beans.factory.xml.DefaultDocumentLoader.loadDocument(DefaultDocumentLoader.java:75)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:396)
... 5 more

You simply haven't put the namespace bean in your config file header : http://docs.spring.io/spring-integration/reference/html/xml.html

Related

WARNING: Exception encountered during context initialization

Before it work but now it is not working.And previously when it worked i use to get session Null in CrediCarddao.java for updating the customer status and inserting new creditcard record into database.
Apr 14, 2017 9:32:36 AM org.springframework.context.support.FileSystemXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.FileSystemXmlApplicationContext#68de145: startup date [Fri Apr 14 09:32:36 CDT 2017]; root of context hierarchy
Apr 14, 2017 9:32:36 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from file [C:\BCJ_DEC_2016\workspace\CoreJava\creditcardprocess\spring.xml]
Apr 14, 2017 9:32:37 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
INFO: Looking for #ControllerAdvice: org.springframework.context.support.FileSystemXmlApplicationContext#68de145: startup date [Fri Apr 14 09:32:36 CDT 2017]; root of context hierarchy
Apr 14, 2017 9:32:37 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
INFO: Looking for #ControllerAdvice: org.springframework.context.support.FileSystemXmlApplicationContext#68de145: startup date [Fri Apr 14 09:32:36 CDT 2017]; root of context hierarchy
Apr 14, 2017 9:32:37 AM org.springframework.context.support.FileSystemXmlApplicationContext refresh
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'creditCardDao' defined in file [C:\BCJ_DEC_2016\workspace\CoreJava\creditcardprocess\target\classes\com\bcj\creditcardprocess\dao\CreditCardDao.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.bcj.creditcardprocess.dao.CreditCardDao]: Constructor threw exception; nested exception is java.lang.NullPointerException
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'creditCardDao' defined in file [C:\BCJ_DEC_2016\workspace\CoreJava\creditcardprocess\target\classes\com\bcj\creditcardprocess\dao\CreditCardDao.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.bcj.creditcardprocess.dao.CreditCardDao]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1155)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.context.support.FileSystemXmlApplicationContext.(FileSystemXmlApplicationContext.java:140)
at org.springframework.context.support.FileSystemXmlApplicationContext.(FileSystemXmlApplicationContext.java:84)
at com.bcj.creditcardprocess.CreditCardMain.main(CreditCardMain.java:15)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.bcj.creditcardprocess.dao.CreditCardDao]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1147)
... 13 more
Caused by: java.lang.NullPointerException
at com.bcj.creditcardprocess.dao.CreditCardDao.(CreditCardDao.java:22)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142)
... 15 more
CreditCardMain.java*
package com.bcj.creditcardprocess;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import com.bcj.creditcardprocess.service.CreditCardService;
public class CreditCardMain {
public static void main(String[] args) {
#SuppressWarnings("resource")
ApplicationContext context = new FileSystemXmlApplicationContext("spring.xml");
CreditCardService obj = (CreditCardService) context.getBean("cCardService");
//CreditCardService cCardService = new CreditCardService();
obj.processCreditCard();
}
}
CreditCardService.java
package com.bcj.creditcardprocess.service;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bcj.creditcardprocess.dao.CreditCardDao;
import com.bcj.creditcardprocess.model.Customer;
#Service
public class CreditCardService {
#Autowired
private CreditCardDao cCardDao;
public void setcCardDao(CreditCardDao cCardDao) {
this.cCardDao = cCardDao;
}
public void processCreditCard() {
List<Customer> customerList = cCardDao.getCustomerList();
// creating a pool of 5 threads
ExecutorService executor = Executors.newFixedThreadPool(5);
for (Iterator iterator = customerList.iterator(); iterator.hasNext();) {
Customer cust = (Customer) iterator.next();
System.out.println(cust);
WorkerThread thread = new WorkerThread();
thread.threadmain(customerList);
//Runnable worker = new WorkerThread(cust);
// calling execute method of ExecutorService
//executor.execute(worker);
/*WorkerThread thread = new WorkerThread();
thread.threadmain(customerList);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("Finished all threads");*/
/*
* List<Object> result = (List<Object>) customerList; Iterator itr =
* result.iterator(); while(itr.hasNext()){ Object[] obj = (Object[])
* itr.next();
*
* System.out.println(String.valueOf(obj[0])+" "+String.valueOf(obj[1]
* ));
*
*/
/*
* for (int i = 0; i < 10; i++) { Runnable worker = new WorkerThread(obj
* ); executor.execute(worker);//calling execute method of
* ExecutorService }
*/
/*executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("Finished all threads");*/
}
}
}
WorkerThread.java
package com.bcj.creditcardprocess.service;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bcj.creditcardprocess.dao.CreditCardDao;
import com.bcj.creditcardprocess.model.CreditCard;
import com.bcj.creditcardprocess.model.Customer;
#Service
public class WorkerThread implements Runnable {
#Autowired
private CreditCardDao cCardDao;
public void setcCardDao(CreditCardDao cCardDao) {
this.cCardDao = cCardDao;
}
public WorkerThread() {
}
WorkerThread(Customer cust2) {
this.cust = cust2;
}
Customer cust;
public void run() {
System.out.println(Thread.currentThread().getName() + " (Start) message = " + cust.getFirstName());
try {
getCutomerDetailsByTextFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " (End)");
}
public synchronized void getCutomerDetailsByTextFile() throws IOException {
FileReader fr = new FileReader("details.txt");
BufferedReader br = new BufferedReader(fr);
String line = "";
while ((line = br.readLine()) != null) {
System.out.println(line);
String[] details = line.split(" ");
if (details[0].equalsIgnoreCase(cust.getFirstName()) && details[1].equalsIgnoreCase(cust.getLastName())
&& details[2].equals(cust.getSsn())) {
System.out.println(" ssn had");
if (Integer.parseInt(details[3]) > 700 && Integer.parseInt(cust.getAnnualIncome()) > 100000) {
CreditCard card = new CreditCard();
card.setCreditLimit(5000);
card.setCustomerId(cust.getId());
generateCardNumber(card, cust);
cust.setStatus("Approved");
} else if (Integer.parseInt(details[3]) > 600 && Integer.parseInt(details[3]) < 700
&& Integer.parseInt(cust.getAnnualIncome()) > 70000) {
CreditCard card = new CreditCard();
card.setCreditLimit(3000);
card.setCustomerId(cust.getId());
generateCardNumber(card, cust);
cust.setStatus("Approved");
} else {
cCardDao.updateCustomer(cust);
cust.setStatus("Declined");
}
break;
}
}
}
public void threadmain(List<Customer> customerList) {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (Iterator iterator = customerList.iterator(); iterator.hasNext();) {
Customer cust = (Customer) iterator.next();
Runnable worker = new WorkerThread(cust);
executor.execute(worker);// calling execute method of
// ExecutorService
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("Finished all threads");
}
private void generateCardNumber(CreditCard cCard, Customer cust) {
Random rand = new Random();
String cardNumber = Integer.toString(rand.nextInt(9999) + 1000) + Integer.toString(rand.nextInt(9999) + 1000)
+ Integer.toString(rand.nextInt(9999) + 1000) + Integer.toString(rand.nextInt(9999) + 1000);
String cvv = Integer.toString(rand.nextInt(999) + 100);
Calendar cal = Calendar.getInstance();
Date today = cal.getTime();
cal.add(Calendar.YEAR, 3); // to get previous year add -1
Date next = cal.getTime();
SimpleDateFormat adf = new SimpleDateFormat("MM/YY");
String expiryDate = adf.format(next);
cCard.setCardNumber(cardNumber);
cCard.setCvv(cvv);
cCard.setExpiryDate(expiryDate);
cCardDao.persistCreditCard(cCard, cust);
}
}
CreditCardDao.java
package com.bcj.creditcardprocess.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.bcj.creditcardprocess.model.CreditCard;
import com.bcj.creditcardprocess.model.Customer;
#Repository
#Transactional
public class CreditCardDao {
#Autowired
private SessionFactory sessionFactory;
private Session session = sessionFactory.getCurrentSession();
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
// Session session = sessionFactory.getCurrentSession();
List<Customer> custs;
public List<Customer> getCustomerList() {
Transaction tx = session.beginTransaction();
List custs = session.createQuery("FROM Customer WHERE status='New'").list();
return custs;
}
public void persistCreditCard(CreditCard cCard, Customer cust) {
int x = cCard.getCustomerId();
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();
session.persist(cCard);
session.update(cust);
System.out.println("customer saved sucessfully" + cCard);
}
public void updateCustomer(Customer cust) {
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();
session.update(cust);
}
}
Spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.bcj.creditcardprocess" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="cCardService" class="com.bcj.creditcardprocess.service.CreditCardService" />
<bean id="cCardDao" class="com.bcj.creditcardprocess.dao.CreditCardDao" />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/citibank" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<!--Hibernate 4 SessionFactory Bean definition -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.bcj.creditcardprocess.model.CreditCard</value>
<value>com.bcj.creditcardprocess.model.Customer</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.hbm2ddl.auto">update
</prop>
<prop key="hibernate.show_sql">true</prop>
<!-- <prop key="hibernate.current_session_context_class">thread</prop> -->
</props>
</property>
</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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.bcj</groupId>
<artifactId>creditcardprocess</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>creditcardprocess</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.3.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
</dependencies>
</project>
Maybe try to change
private Session session = sessionFactory.getCurrentSession();
to a function
public Session getSession() {
return sessionFactory.getCurrentSession();
}
I am thinking during the class initialization, the class is trying initialize private Session session. And sessionFactory is not ready yet.
Your getSessionFactory() in CreditCardDao.java is throwing the nullPointerExceptionbecause You haven't initialized the SessionFactory so it's initialy pointing to null.
You would do that like this:
private SessionFactory sessionFactory=//build sessionfactory code
Note that the SessionFactoryshould be created once only, you can use the singleton design pattern for that.

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>

Spring not able to inject values through property tag

I am using simple setter injection for setting values to a varaible in a class
But when i try to run the application, the object returns me null values
What could be the reason?
Below are the files.
Spring.XML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans2.0.dtd">
<beans>
<bean id = "triangle" class="com.test.Triangle">
<property name = "type" value = "Equilateral" />
</bean>
</beans>
Triangle.java
public class Triangle {
private String type;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public void draw() {
System.out.println(getType() + " Triangle drawn");
}
}
DrawingApplication.java
package com.test;
public class DrawingApplication {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Spring.xml");
Triangle t = (Triangle) context.getBean("triangle");
t.draw();
}
}
I tried to replicate the problem statement. This is my package structure:
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id = "triangle" class="com.test.Triangle">
<property name = "type" value = "Equilateral" />
</bean>
</beans>
DrawingApplication.java:
package com.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DrawingApplication {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Spring.xml");
Triangle t = (Triangle) context.getBean("triangle");
t.draw();
}
}
Triangle.java:
package com.test;
public class Triangle {
private String type;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public void draw() {
System.out.println(getType() + " Triangle drawn");
}
}
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.test</groupId>
<artifactId>Example</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>Example</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 ran the above code and got following output:
Jun 17, 2014 12:17:21 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#693a317a: startup date [Tue Jun 17 12:17:21 GMT+05:30 2014]; root of context hierarchy
Jun 17, 2014 12:17:21 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [Spring.xml]
Jun 17, 2014 12:17:21 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#5954864a: defining beans [triangle]; root of factory hierarchy
Equilateral Triangle drawn
I got the expected output, so looks like there is some issue with the classpath and the location of spring.xml file.

How would I display this in main(String[] args) and how do I hook up these classes and/or constructors in xml?

I am trying to validate if a String has a number associated with it, and rejecting the value if it has a number. It is my first time using Spring Validation, and I have struggled for days with getting it all set up properly. I want the string to print out if it doesn't contain a number, but be rejected by the validator if it does. I am also unsure about the paramater being the value of target. I am unsure of how all of that works. Here is what I have so far:
#Component
public class StringValidator implements Validator
{
public boolean supports(Class<?> clazz)
{
return Main.class.isAssignableFrom(clazz);
}
#Autowired
public void validate(Object target, Errors errors)
{
//the 2nd parameter in ValidationUtils needs to be the string the validator takes in, which should be a set value from Main...?
Main main = (Main) target;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, String.valueOf(main), AppConstants.NULL_ERROR_MSG);
if(!errors.hasErrors())
{
boolean containsNbr = false;
for(char c : String.valueOf(main).toCharArray())
{
if(Character.isDigit(c))
{
containsNbr = true;
break;
}
}
if(containsNbr)
{
errors.rejectValue(String.valueOf(main), AppConstants.NUMBERS_ERROR_MSG);
}
else
{
System.out.println(String.valueOf(main));
}
}
}
}
applicationContext.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:util="http://www.springframework.org/schema/util"
xsi:schemaLocation=
"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">
<context:component-scan base-package="com.imports.validationexample"/>
<bean id="main" class="com.imports.validationexample.application" />
<bean id ="springValidator" class="com.imports.validationexample.validation.StringValidator" />
<bean id="main" class="com.imports.validationexample.application.main">
<property name="string" value="Forty8"/>
</bean>
<bean id="validate" class="org.springframework.validation.Validator">
<constructor-arg ref="Validator"/>
</bean>
</beans>
I can't seem to hook it up properly, and am unsure how to represent it in my Main class. Any help is appreciated!
Here's one approach (maybe it can be improved):
app-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="stringValidator" class="com.foo.bar.StringValidator" />
<bean id="myStringHoldingBean" class="com.foo.bar.MyStringHoldingBean">
<property name="string" value="Faulty m3ssage" />
</bean>
</beans>
Your main class:
package com.foo.bar;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("app-context.xml");
MyStringHoldingBean bean = (MyStringHoldingBean) ctx.getBean("myStringHoldingBean");
Errors errors = new BeanPropertyBindingResult(bean, "myStringHoldingBean");
Validator validator = (Validator)ctx.getBean("stringValidator");
ValidationUtils.invokeValidator(validator, bean, errors);
if (errors.hasErrors()) { System.out.println("ERRORS"); }
}
}
MyStringHoldingBean:
package com.foo.bar;
public class MyStringHoldingBean {
private String string;
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
}
StringValidator:
package com.foo.bar;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
public class StringValidator implements Validator {
public boolean supports(Class<?> clazz) {
return MyStringHoldingBean.class.isAssignableFrom(clazz);
}
public void validate(Object target, Errors errors) {
MyStringHoldingBean main = (MyStringHoldingBean) target;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "string", "Not null string, please!");
if (!errors.hasErrors()) {
boolean containsNbr = false;
for (char c : main.getString().toCharArray()) {
if (Character.isDigit(c)) {
containsNbr = true;
break;
}
}
if (containsNbr) {
errors.rejectValue("string", "String contains numbers!");
}
else {
System.out.println(main.getString());
}
}
}
}
pom.xml
<properties>
<spring.framework.version>3.2.6.RELEASE</spring.framework.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.1.Final</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
</dependencies>
Spring Validation is about validating beans, so this is why I put that "string" inside a class (MyStringHoldingBean).

Spring Maven Project

Hey guys I am having a problem when I try to run this application. I do not receive a compilation error, just runtime ones. I think I am missing something but I am not sure, can someone help me understand where I've gone wrong? From what I can see the sessionFactory bean in the applicationContext.xml is not being created. Here is my code:
Main
package com.apress.flexjava.usermanager.business;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.apress.flexjava.usermanager.dao.UserDao;
import com.apress.flexjava.usermanager.model.User;
public class Main {
public static void main(String [] args){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao = (UserDao)context.getBean("userDao");
List<User> users = userDao.findAll();
for (User user : users) {
System.out.println(user.getForename() + " " + user.getSurname());
}
}
}
______________________________________________________________________________________
UserDao
package com.apress.flexjava.usermanager.dao;
import java.util.List;
import com.apress.flexjava.usermanager.model.User;
public interface UserDao {
List<User> findAll();
}
__________________________________________________________________________________
UserDaoSpringJdbcImpl
package com.apress.flexjava.usermanager.dao.jdbc;
import java.util.List;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;
import com.apress.flexjava.usermanager.dao.UserDao;
import com.apress.flexjava.usermanager.model.User;
public class UserDaoSpringJdbcImpl extends SimpleJdbcDaoSupport implements UserDao{
public List<User> findAll(){
String sql= "SELECT * FROM users";
return getSimpleJdbcTemplate().query(sql, ParameterizedBeanPropertyRowMapper.newInstance(User.class));
}
}
____________________________________________________________________________________
User
package com.apress.flexjava.usermanager.model;
public class User {
private int userid;
private String forename;
private String surname;
public User(){}
public User(int userid, String forename, String surname){
this.userid = userid;
this.forename = forename;
this.surname = surname;
}
public User(String forename, String surname){
this.forename = forename;
this.surname = surname;
}
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getForename() {
return forename;
}
public void setForename(String forename) {
this.forename = forename;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
}
_________________________________________________________________________________
applicationContext.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:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
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/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
http://www.springframework.org/schema/lang
http://www.springframework.org/schema/lang/spring-lang-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-2.5.xsd">
<!-- #Required processor -->
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor" />
<!-- Exception translation bean post processor -->
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name= "driverClassName" value="${jdbc.driverClassName}"/>
<property name= "url" value="${jdbc.url}"/>
<property name= "username" value="${jdbc.username}"/>
<property name= "password" value="${jdbc.password}"/>
</bean>
<bean name="UserDao" class="com.apress.flexjava.usermanager.dao.jdbc.UserDaoSpringJdbcImpl">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- Hibernate SessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name = "configLocation" value = "classpath:hibernate.cfg.xml"/>
<property name = "hibernateProperties">
<value>
hibernate.dialect= org.hibernate.dialect.MySQLDialect
hibernate.query.substitutions=true 'Y', false 'N'
hibernate.cache.use_second_level_cache=true
hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
hibernate.hbm2ddl.auto=update
hibernate.use_sql_comments=true
hibernate.show_sql=true
</value>
</property>
</bean>
</beans>
________________________________________________________________________________________
jdbc properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/usermanager_test
jdbc.username=root
jdbc.password=password
_______________________________________________________________________________________
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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.apress.flexjava</groupId>
<artifactId>usermanager</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>UserManager</name>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>2.5.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>2.5.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
____________________________________________________________________________
Console Runtime Error:
Apr 17, 2012 11:51:49 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#179c285: display name [org.springframework.context.support.ClassPathXmlApplicationContext#179c285]; startup date [Tue Apr 17 23:51:49 BOT 2012]; root of context hierarchy
Apr 17, 2012 11:51:49 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
Apr 17, 2012 11:51:49 PM org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory
INFO: Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext#179c285]: org.springframework.beans.factory.support.DefaultListableBeanFactory#16a786
Apr 17, 2012 11:51:49 PM org.springframework.core.io.support.PropertiesLoaderSupport loadProperties
INFO: Loading properties file from class path resource [jdbc.properties]
Apr 17, 2012 11:51:49 PM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#16a786: defining beans [org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor#0,org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0,propertyConfigurer,dataSource,UserDao,sessionFactory]; root of factory hierarchy
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0' defined in class path resource [applicationContext.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/MappingException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:480)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:880)
at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:596)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:365)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.apress.flexjava.usermanager.business.Main.main(Main.java:15)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/MappingException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:883)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:839)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:440)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:308)
at org.springframework.beans.factory.BeanFactoryUtils.beansOfTypeIncludingAncestors(BeanFactoryUtils.java:270)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.detectPersistenceExceptionTranslators(PersistenceExceptionTranslationInterceptor.java:122)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.<init>(PersistenceExceptionTranslationInterceptor.java:78)
at org.springframework.dao.annotation.PersistenceExceptionTranslationAdvisor.<init>(PersistenceExceptionTranslationAdvisor.java:70)
at org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor.setBeanFactory(PersistenceExceptionTranslationPostProcessor.java:97)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1326)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473)
... 14 more
Caused by: java.lang.NoClassDefFoundError: org/hibernate/MappingException
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389)
at java.lang.Class.getConstructor0(Class.java:2699)
at java.lang.Class.getDeclaredConstructor(Class.java:1985)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:54)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:877)
... 32 more
Caused by: java.lang.ClassNotFoundException: org.hibernate.MappingException
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
... 38 more
This exception:
Caused by: java.lang.ClassNotFoundException:
org.hibernate.MappingException
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
... 38 more
Indicates that you are missing the Hibernate libraries from your project. Try adding the following to your POM:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
<version>3.5.4-Final</version>
</dependency>

Categories