Hello i am using constructor injection in my spring demo app when i run this program i got :
java.lang.IllegalArgumentException exception
Anyone have solution where i am wong and whenever i run same program using setter injection it runs perfectly .
Here is my EmployeeBean.java
package cris;
public class Employee {
private int id;
private String name;
public Employee() { }
public Employee(int id,String name) {
this.id=id;
this.name=name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
void show() {
System.out.println(id+" "+name);
}
}
Here is my Address Bean using setter injection
package cris;
public class Address {
private String city,state,country;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String toString()
{
return city+" "+state+" "+country;
}
}
Here is my spring.xml ie spring config file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="a1" class="cris.Address">
<property name="city" value="Tikamgarh"></property>
<property name="state" value="Mp"></property>
<property name="country" value="India"></property>
</bean>
<bean id="e" class="cris.Employee">
<constructor-arg type="int" value="12"></constructor-arg>
<constructor-arg type="String" value="anil"></constructor-arg>
</bean>
</beans>
And here is my Application Main Method
package cris;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("cris/spring.xml");
Employee emp = (Employee)context.getBean("e");
emp.show();
}
}
kindly provide me suggestion where i am wrong so i will catch the exception thanks
The Exception:
Apr 03, 2017 4:16:16 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#27f8302d: startup date [Mon Apr 03 16:16:16 IST 2017]; root of context hierarchy
Apr 03, 2017 4:16:16 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [cris/spring.xml]
Apr 03, 2017 4:16:16 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#17550481: defining beans [a1,e]; root of factory hierarchy
Exception in thread "main" java.lang.IllegalArgumentException
at org.springframework.asm.ClassReader.<init>(Unknown Source)
at org.springframework.asm.ClassReader.<init>(Unknown Source)
at org.springframework.asm.ClassReader.<init>(Unknown Source)
at org.springframework.core.LocalVariableTableParameterNameDiscoverer.inspectClass(LocalVariableTableParameterNameDiscoverer.java:112)
at org.springframework.core.LocalVariableTableParameterNameDiscoverer.getParameterNames(LocalVariableTableParameterNameDiscoverer.java:86)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:193)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1049)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:953)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:490)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:607)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at cris.Test.main(Test.java:8)
When filling POJO's, (for what I know) Spring calls the no-arg constructor by default. If you decide to write a cTor with parameters yourself, you will not get a default cTor generated and you'll have to add a no-arg cTor for spring yourself.
public Employee() { }
Add type to your constructor-arg
<constructor-arg type="int" value="12" />
and
<constructor-arg type="java.lang.String" value="anil" />
EDIT
or you can use indexes
<constructor-arg index="0" value="12" />
and
<constructor-arg index="1" value="anil" />
Have spring.xml like this:
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="a1" class="cris.Address">
<property name="city" value="Tikamgarh"></property>
<property name="state" value="Mp"></property>
<property name="country" value="India"></property>
</bean>
<bean id="e" class="cris.Employee">
<constructor-arg type="int" value="12"></constructor-arg>
<constructor-arg type="String" value="anil"></constructor-arg>
</bean>
</beans>
EDIT
My example:
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="bean" class="Bean">
<constructor-arg index="0" value="Test"/>
<constructor-arg index="1" value="2"/>
</bean>
</beans>
Bean.java
public class Bean {
private String test1;
private int test2;
public Bean(String test1, int test2) {
this.test1 = test1;
this.test2 = test2;
}
public String getTest1() {
return test1;
}
public void setTest1(String test1) {
this.test1 = test1;
}
public int getTest2() {
return test2;
}
public void setTest2(int test2) {
this.test2 = test2;
}
#Override
public String toString() {
return "Bean{" +
"test1='" + test1 + '\'' +
", test2=" + test2 +
'}';
}
}
Test.java
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
final ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
final Bean bean = (Bean) ctx.getBean("bean");
System.out.println(bean.toString());
}
}
prints:
Bean{test1='Test', test2=2}
I had the same issue and can't figure out why until I read each comment in current post and found out...
Using Spring 3.* and Java 11 that is a compatibility issue. When I downloaded the latest version (Spring 5.*) and set to the CLASSPATH. Then everything works.
Related
I was trying to understand the working of HibernateTemplate in Spring-hibernate environment. Since I am new to HibernateTemplate, I feel difficult to understand the errors. In my project I have used all the jar files availabe in spring-framework-4.0.3 and hibernate-4.3.5. Some of the additional jars used in this project are:
*cglib-nodep-2.1.3.jar
*commons-logging.jar
*ojdbc14.jar
*tomcat-dbcp-7.0.30.jar
Following java/xml files were used :
StudentDaoInterface.java
package dao;
import java.util.List;
import model.Student;
public interface StudentDaoInterface {
public int save(Student st);
public boolean update(Student st);
public boolean delete(Student st);
public Student findbyPK(int pk);
public List<Student> findAllUsingHQL();
public List<Student> findAllUsingCriteria();
}
StudentDaoImplHT.java
package dao;
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.orm.hibernate4.HibernateTemplate;
import model.Student;
public class StudentDaoImplHT implements StudentDaoInterface {
private HibernateTemplate ht;
public void setHt(HibernateTemplate ht) {
this.ht = ht;
}
#Override
public int save(Student st) {
int i=(Integer)ht.save(st);
return i;
}
#Override
public boolean update(Student st) {
ht.update(st);
return true;
}
#Override
public boolean delete(Student st) {
ht.delete(st);
return true;
}
#Override
public Student findbyPK(int pk) {
Student st = (Student)ht.get(Student.class,pk);
return st;
}
#Override
public List<Student> findAllUsingHQL() {
List list = ht.find("from student");
return list;
}
#Override
public List<Student> findAllUsingCriteria() {
DetachedCriteria dc = DetachedCriteria.forClass(Student.class);
List list = ht.findByCriteria(dc);
return list;
}
}
Student.java
package model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="student",schema="system")
public class Student {
#Id
private int id;
private String name;
private String email;
private String address;
public Student(int id, String name, String email, String address) {
super();
this.id = id;
this.name = name;
this.email = email;
this.address = address;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setEmail(String email) {
this.email = email;
}
public void setAddress(String address) {
this.address = address;
}
}
test.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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<bean id="bds" class="org.apache.tomcat.dbcp.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:#localhost:1521:xe"/>
<property name="username" value="system"/>
<property name="password" value="manager"/>
<property name="maxActive" value="15"/>
<property name="maxIdle" value="5"/>
<property name="maxWait" value="5000"/>
</bean>
<bean id="sf" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="bds" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>model.Student</value>
</list>
</property>
</bean>
<bean id="ht" class="org.springframework.orm.hibernate4.HibernateTemplate">
<property name="sessionFactory" ref="sf" />
</bean>
<bean id="dao" class="dao.StudentDaoImplHT">
<property name="ht" ref="ht" />
</bean>
</beans>
SaveClient.java
package test;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import dao.StudentDaoInterface;
import model.Student;
public class SaveClient {
public static void main(String[] args){
ConfigurableApplicationContext cap = new ClassPathXmlApplicationContext("resources/test.xml");
StudentDaoInterface dao = (StudentDaoInterface)cap.getBean("dao");
Student st = new Student(222,"bbb","bbb#gmail.com","hyd");
dao.save(st);
System.out.println("success");
cap.close();
}
}
After running the code SaveClient.java I face following errors:
Dec 17, 2017 9:27:52 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#3f8f9dd6: startup date [Sun Dec 17 09:27:52 IST 2017]; root of context hierarchy
Dec 17, 2017 9:27:52 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [resources/test.xml]
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sf' defined in class path resource [resources/test.xml]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: [Lorg/hibernate/engine/FilterDefinition;
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:547)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:684)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at test.SaveClient.main(SaveClient.java:13)
Caused by: java.lang.NoClassDefFoundError: [Lorg/hibernate/engine/FilterDefinition;
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
at java.lang.Class.privateGetPublicMethods(Unknown Source)
at java.lang.Class.privateGetPublicMethods(Unknown Source)
at java.lang.Class.getMethods(Unknown Source)
at org.springframework.beans.ExtendedBeanInfoFactory.supports(ExtendedBeanInfoFactory.java:54)
at org.springframework.beans.ExtendedBeanInfoFactory.getBeanInfo(ExtendedBeanInfoFactory.java:46)
at org.springframework.beans.CachedIntrospectionResults.<init>(CachedIntrospectionResults.java:275)
at org.springframework.beans.CachedIntrospectionResults.forClass(CachedIntrospectionResults.java:188)
at org.springframework.beans.BeanWrapperImpl.getCachedIntrospectionResults(BeanWrapperImpl.java:327)
at org.springframework.beans.BeanWrapperImpl.getPropertyDescriptorInternal(BeanWrapperImpl.java:359)
at org.springframework.beans.BeanWrapperImpl.isWritableProperty(BeanWrapperImpl.java:438)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1458)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1197)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
... 11 more
Caused by: java.lang.ClassNotFoundException: org.hibernate.engine.FilterDefinition
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 26 more
You should use org.springframework.orm.hibernate4.LocalSessionFactoryBean instead of org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean. But in doc, it says that the following, so be careful about your Spring version or decrease your Hibernate from 4.3.5. to 4.2 or 4.1 as documentation suggests.
This variant of LocalSessionFactoryBean requires Hibernate 4.0 or higher. Note that this version is not compatible with the (the quite refactored) Hibernate 4.3 yet; please upgrade to the Spring 4.0 line for full Hibernate 4.3 support. We recommend using this version with the latest Hibernate 4.1.x or 4.2.x releases.
I am trying to integrate the spring and hibernate.I want to save my data into database using this functionality. My files are attached as follows.
Employee.java
package springhibernate;
public class Employee {
private int id;
private String name;
private float salary;
public Employee() {
super();
}
public Employee(int id, String name, float salary) {
super();
this.id = id;
this.name = name;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
}
employee.hbm.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.javatpoint.Employee" table="emp558">
<id name="id">
<generator class="assigned"></generator>
</id>
<property name="name"></property>
<property name="salary"></property>
</class>
</hibernate-mapping>
EmployeeDao.java
package springhibernate;
import java.util.ArrayList;
import java.util.List;
import org.springframework.orm.hibernate3.HibernateTemplate;
public class EmployeeDao {
HibernateTemplate template;
public void setTemplate(HibernateTemplate template)
{
this.template = template;
}
//method to save employees
public void saveEmployee(Employee e)
{
template.save(e);
}
//method to update employees
public void updateEmployee(Employee e)
{
template.update(e);
}
//method to delete employees
public void deleteEmployee(Employee e)
{
template.delete(e);
}
//method to return employee of given id
public Employee getById(int id)
{
Employee e = (Employee)template.get(Employee.class, id);
return e;
}
//method to return all employees
public List<Employee> getEmployees()
{
List<Employee> list = new ArrayList<Employee>();
list = template.loadAll(Employee.class);
return list;
}
}
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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:#localhost:1521/XE"></property>
<property name="username" value="system"></property>
<property name="password" value="manager"></property>
</bean>
<bean id="mysessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mappingResources">
<list>
<value>employee.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="template" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="mysessionFactory"></property>
</bean>
<bean id="d" class="springhibernate.EmployeeDao">
<property name="template" ref="template"></property>
</bean>
</beans>
InsertTest.java
package springhibernate;
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;
#SuppressWarnings("deprecation")
public class InsertTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Resource r = new ClassPathResource("applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(r);
EmployeeDao dao = (EmployeeDao)factory.getBean("d");
Employee e = new Employee();
e.setId(114);
e.setName("varun");
e.setSalary(5000);
dao.saveEmployee(e);
}
}
now while running the above code i am getting the exceptions as follows. i included/ added all the jar files whatever are needed. i also saw some related questions on the stackoverflow but didn't get the proper hints.
errors
Oct 23, 2017 3:12:45 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'd' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'template' while setting bean property 'template'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'template' defined in class path resource [applicationContext.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/JDBCException
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1469)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at springhibernate.InsertTest.main(InsertTest.java:15)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'template' defined in class path resource [applicationContext.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/JDBCException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1093)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1038)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351)
... 10 more
Caused by: java.lang.NoClassDefFoundError: org/hibernate/JDBCException
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Unknown Source)
at java.lang.Class.getConstructor0(Unknown Source)
at java.lang.Class.getDeclaredConstructor(Unknown Source)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:80)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1086)
... 18 more
Caused by: java.lang.ClassNotFoundException: org.hibernate.JDBCException
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 24 more**
can anyone help me to getting out from this errors/exceptions.
Thanks in advance.
I am not exactly sure whether this solution will work just a small hunch.
Replace :
Resource r = new ClassPathResource("applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(r);
EmployeeDao dao = (EmployeeDao)factory.getBean("d");
with :
ApplicationContext r = new ClassPathXMLContext("applicationContext.xml);
Employee dao = r.getBean("d");
I am trying to use #Autowired Annotation in Spring for Dependency Injection
through a simple program but i give me following error
Exception in thread "main" java.lang.NullPointerException
at Customer.d(Customer.java:8)
at Main.main(Main.java:12)
Through xml configuration it give me correct result.
My xml file
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean id="person" class="Person">
<property name="name" value="khan"/>
</bean>
<bean id="cust" class="Customer"></bean>
</beans>
Customer Class
public class Customer {
#Autowired
private Person p;
public void display(){
System.out.println(p.getName());
}
}
Person Class
public class Person {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String name;
}
Main Class
public class Main {
public static void main(String[] a) {
Resource r=new ClassPathResource("SpringXml.xml");
BeanFactory factory=new XmlBeanFactory(r);
Customer c=(Customer)factory.getBean("cust");
c.display();
}
}
Try like this
public static void main(String[] args) throws Exception {
ApplicationContext context= new ClassPathXmlApplicationContext("SpringXml.xml");
Customer c = (Customer) context.getBean("cust");
c.display();
}
try this :
<bean id="person" class="com.yourpackage.Person">
<property name="name" value="khan"/>
</bean>
<bean id="cust" class="com.yourpackage.Customer">
<property name="p" ref="person"/>
</bean>
dont forget to add your fullpath class package
I have a simple spring jdbc program but when I run the program I get a queryTimeOut exception.
Here is the complete stackTrace
Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/dao/QueryTimeoutException
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.<init>(SQLErrorCodeSQLExceptionTranslator.java:87)
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.<init>(SQLErrorCodeSQLExceptionTranslator.java:103)
at org.springframework.jdbc.support.JdbcAccessor.getExceptionTranslator(JdbcAccessor.java:99)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:407)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:519)
at com.test.spring.EmployeeDao.saveEmployee(EmployeeDao.java:14)
at com.test.spring.Test.main(Test.java:13)
Caused by: java.lang.ClassNotFoundException: org.springframework.dao.QueryTimeoutException
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 7 more
Table:
create table employee(emp_name varchar2(30),address varchar2(30),salery number(10),emp_id number(10));
Employee.java:
package com.test.spring;
public class Employee {
private String emp_name;
private String address;
private int salery;
private int emp_id;
public Employee()
{
}
public Employee(String emp_name,int emp_id)
{
this.emp_name=emp_name;
this.emp_id=emp_id;
}
public Employee(String emp_name,String address,int salery,int emp_id)
{
this.emp_name=emp_name;
this.address=address;
this.salery=salery;
this.emp_id=emp_id;
}
public String getEmp_name() {
return emp_name;
}
public void setEmp_name(String emp_name) {
this.emp_name = emp_name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getSalery() {
return salery;
}
public void setSalery(int salery) {
this.salery = salery;
}
public int getEmp_id() {
return emp_id;
}
public void setEmp_id(int emp_id) {
this.emp_id = emp_id;
}
}
EmployeeDao.java:
package com.test.spring;
import org.springframework.jdbc.core.JdbcTemplate;
public class EmployeeDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public int saveEmployee(Employee e){
//String query="insert into employee (emp_name,address,salery,emp_id)values(?,?,?,?)";//not getting any exception
String query="insert into employee (emp_name,address,salery,emp_id)values("+e.getEmp_name()+","+e.getAddress()+","+e.getSalery()+","+e.getEmp_id()+")";//getting queryTimeOutException
return jdbcTemplate.update(query);
}
}
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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#localhost:1521:xe" />
<property name="username" value="system" />
<property name="password" value="mysql" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="edao" class="com.test.spring.EmployeeDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
</beans>
Test.java:
package com.test.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
EmployeeDao dao=(EmployeeDao)ctx.getBean("edao");
int status=dao.saveEmployee(new Employee("Amit","Pingla",35000,102));
System.out.println(status);
}
}
The error points out that you're missing a class from your classpath. It doesn't mean that specific exception would get thrown during that particular invocation; but it simply doesn't find the class for it.
To add the QueryTimeoutException class in your classpath, you need to add a dependency on the spring-tx module.
You can add this dependency
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
If your are using maven or this one
[group: 'org.springframework', name: 'spring-tx', version: '4.1.6.RELEASE'],
if you are using gradle.
JdbcTemplate has queryTimeout property, you can try to configure it to a desired value.
I am new to the concepts of Spring and Hibernate.
I am using collections in my simple spring program. My idea is to store an author name, address and id into collection. It's a simple spring framework but I am struck with one error.
spring-model.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="book" class="com.vishal.Book">
<property name="author ">
<list>
<ref bean="book1 " />
<ref bean="book2 " />
<ref bean="book3 " />
</list>
</property>
</bean>
<bean id="book1" class="com.vishal.Book">
<property name="name" value="mark twain" />
<property name="address" value="London" />
<property name="id" value="230" />
</bean>
<bean id="book2" class="com.vishal.Book">
<property name="name" value="gutav friedman" />
<property name="address" value="Germany" />
<property name="id" value="231" />
</bean>
<bean id="book3" class="com.vishal.Book">
<property name="name" value=" Erastothe " />
<property name="address" value="spain" />
<property name="id" value="232" />
</bean>
</beans>
main class
package com.vishal;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Springmain {
#SuppressWarnings("resource")
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
"spring-model.xml");
Book book = (Book) context.getBean("book");
book.authorName();
}
}
book.java
package com.vishal;
import java.util.List;
public class Book {
private List<Author> author;
public List<Author> getAuthor() {
return author;
}
public void setAuthor(List<Author> author) {
this.author = author;
}
public void authorName() {
for (Author authors : author)
System.out.println(authors.getAddress() + authors.getId()
+ authors.getName());
}
}
author class
package com.vishal;
public class Author {
private String name;
private String address;
private int id;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Following is the error which I a getting
Jun 10, 2013 11:29:36 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#161d36b: startup date [Mon Jun 10 11:29:36 IST 2013]; root of context hierarchy
Jun 10, 2013 11:29:36 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring-model.xml]
Jun 10, 2013 11:29:37 AM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#1b5998f: defining beans [book,book1,book2,book3]; root of factory hierarchy
Jun 10, 2013 11:29:37 AM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#1b5998f: defining beans [book,book1,book2,book3]; root of factory hierarchy
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'book' defined in class path resource [spring-model.xml]: Cannot resolve reference to bean 'book1 ' while setting bean property 'author ' with key [0]; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'book1 ' is defined
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:329)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:107)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:353)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:154)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1393)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1134)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:522)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:626)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.vishal.Springmain.main(Springmain.java:10)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'book1 ' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:568)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1102)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:278)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:323)
... 17 more
There is space in bean references:
whereas actual bean name has no space:
Also as Luiggi suggested Bean definition needs to corrected.
Please check this.
In your Book class you have a List<Author> but in your spring-model.xml file you refer to book1, book2 and book3 as instances of Book, not from Author probably due for copy/paste process and forgetting the most important step: adapt what you pasted.
Just to show an example:
<bean id="book1" class="com.vishal.Book">
It should be
<bean id="book1" class="com.vishal.Author">
Also, you're referring to other beans using
<ref bean="book1 " />
There's a white space in the end that should be trimmed. It should be
<ref bean="book1" />
Similar for other bookX references in your spring-model.xml file.