spring batch AsynchJob Launcher ,Error in setting job repo - spring

Hi below is my configuration for creating asynchlob launcher
<bean id="jobLauncher"
class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="jobRepository" ref="&jobRepository" />
<property name="taskExecutor" ref="taskExecutor" />
</bean>
<bean id="taskExecutor" class="org.springframework.core.task.SimpleAsyncTaskExecutor" />
<bean id="jobRepository" class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean" />
i'm getting below error
Error creating bean with name 'batchJobLauncher': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.batch.core.launch.support.SimpleJobLauncher com.batch.launcher.BatchJobLauncher.asyncJobLauncher; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobLauncher' defined in ServletContext resource [/WEB-INF/BatchConfig.xml]: Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean' to required type 'org.springframework.batch.core.repository.JobRepository' for property 'jobRepository'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean] to required type [org.springframework.batch.core.repository.JobRepository] for property 'jobRepository': no matching editors or conversion strategy found
.....
caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean' to required type 'org.springframework.batch.core.repository.JobRepository' for property 'jobRepository'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean] to required type [org.springframework.batch.core.repository.JobRepository] for property 'jobRepository': no matching editors or conversion strategy found
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:476) [spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:512) [spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:506) [spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1523) [spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1482) [spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1222) [spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) [spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
... 54 more
Caused by: java.lang.IllegalStateException: Cannot convert value of type [org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean] to required type [org.springframework.batch.core.repository.JobRepository] for property 'jobRepository': no matching editors or conversion strategy found
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:287) [spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:461) [spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
... 60 more
i tried without & also.
error like this
13:58:59,346 WARN [org.springframework.web.context.support.XmlWebApplicationContext] (ServerService Thread Pool -- 58) Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobBuilders' defined in class path resource [org/springframework/batch/core/configuration/annotation/SimpleBatchConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.batch.core.configuration.annotation.JobBuilderFactory]: Factory method 'jobBuilders' threw exception; nested exception is java.lang.ClassCastException: org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean$$EnhancerBySpringCGLIB$$99e29281 cannot be cast to org.springframework.batch.core.repository.JobRepository
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) [spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1119)

Here is a working example made from http://www.mkyong.com/spring-batch/spring-batch-hello-world-example/ and tested on wildfly 9.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:batch="http://www.springframework.org/schema/batch"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/batch
http://www.springframework.org/schema/batch/spring-batch-2.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
">
<bean id="report" class="Report" scope="prototype" />
<bean id="jobRepository"
class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
<property name="transactionManager" ref="transactionManager" />
</bean>
<batch:job id="helloWorldJob">
<batch:step id="step1">
<batch:tasklet>
<batch:chunk reader="cvsItemReader" writer="xmlItemWriter"
commit-interval="10">
</batch:chunk>
</batch:tasklet>
</batch:step>
</batch:job>
<bean id="jobLauncher"
class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="jobRepository" ref="jobRepository" />
<property name="taskExecutor" ref="taskExecutor" />
</bean>
<bean id="cvsItemReader" class="org.springframework.batch.item.file.FlatFileItemReader">
<property name="resource" value="classpath:report.csv" />
<property name="lineMapper">
<bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
<property name="lineTokenizer">
<bean
class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer">
<property name="names" value="id,sales,qty,staffName,date" />
</bean>
</property>
<property name="fieldSetMapper">
<bean
class="org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper">
<property name="prototypeBeanName" value="report" />
</bean>
</property>
</bean>
</property>
</bean>
<bean id="xmlItemWriter" class="org.springframework.batch.item.xml.StaxEventItemWriter">
<property name="resource" value="file:/home/username/report.xml" />
<property name="marshaller" ref="reportMarshaller" />
<property name="rootTagName" value="report" />
</bean>
<bean id="reportMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>Report</value>
</list>
</property>
</bean>
<bean id="taskExecutor" class="org.springframework.core.task.SimpleAsyncTaskExecutor" />
<bean id="transactionManager"
class="org.springframework.batch.support.transaction.ResourcelessTransactionManager" />
</beans>
Report.java:
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "record")
public class Report {
private int id;
private String sales;
private int qty;
private String staffName;
private String date;
#XmlAttribute(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#XmlElement(name = "sales")
public String getSales() {
return sales;
}
public void setSales(String sales) {
this.sales = sales;
}
#XmlElement(name = "qty")
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
#XmlElement(name = "staffName")
public String getStaffName() {
return staffName;
}
public void setStaffName(String staffName) {
this.staffName = staffName;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
#Override
public String toString() {
return "Report [id=" + id + ", sales=" + sales
+ ", qty=" + qty + ", staffName=" + staffName + "]";
}
}
To run use a servlet with the following code:
ApplicationContext context =
new ClassPathXmlApplicationContext("job.xml");
JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
Job job = (Job) context.getBean("helloWorldJob");
try {
org.springframework.batch.core.JobExecution execution = jobLauncher.run(job, new JobParameters());
System.out.println("Exit Status : " + execution.getStatus());
} catch (Exception e) {
e.printStackTrace();
}

Related

[Spring]create an abstract bean for a non abstract class

with this config for Spring framework (4.2.5.RELEASE version):
<bean id="Filter" class="net....StreamFilter" abstract="true">
<property name="begin" value="3" />
<property name="end" value="5" />
</bean>
<bean id="D0Filter" parent="Filter">
<property name="value" value="D0" />
</bean>
and my StreamFilter class is like:
public class StreamFilter {
/** debut du filtre */
private int begin;
/** fin du filtre */
private int end;
private String value;
public Object convert(#Body final Exchange exchange) {
// my code
}
//
// getter & setter
//
}
i have this error:
Exception in thread "main"
org.springframework.beans.factory.BeanIsAbstractException: Error
creating bean with name 'DFIFilter': Bean definition is abstract at
org.springframework.beans.factory.support.AbstractBeanFactory.checkMergedBeanDefinition(AbstractBeanFactory.java:1288)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:285)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at
org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1054)
......
thanks for your responses

CustomDateEditor not working in Spring 4.1.6

I am using a Date dob; field in my pojo class in spring 4.1.6 using maven
below are the files associated with my app.
// this is my pojo class.
package com.aamir;
import java.util.Date;
public class Student {
private String firstName;
private Date dob;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
}
// this is my client class
package com.aamir;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ClientStud1 {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student student = (Student) context.getBean("s1");
System.out.println(student.getFirstName());
System.out.println(student.getDob());
}
}
// and finally this is my beans.xml file
<?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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="s1" class="com.aamir.Student">
<property name="firstName" value="aamir"/>
<property name="dob" value="12-12-1996"/>
</bean>
<bean id="dateEditor"
class="org.springframework.beans.propertyeditors.CustomDateEditor">
<constructor-arg>
<bean class="java.text.SimpleDateFormat">
<constructor-arg value="dd-MM-yyyy"/>
</bean>
</constructor-arg>
<constructor-arg value="true"/>
</bean>
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.util.Date" value-ref="dateEditor"/>
</map>
</property>
</bean>
</beans>
and I get this exception every time I try to run the client
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.beans.factory.config.CustomEditorConfigurer#0' defined in class path resource [beans.xml]:
Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type 'java.util.LinkedHashMap' to required type 'java.util.Map' for property 'customEditors'; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type [org.springframework.beans.propertyeditors.CustomDateEditor] to required type [java.lang.Class] for property 'customEditors[java.util.Date]': PropertyEditor [org.springframework.beans.propertyeditors.ClassEditor] returned inappropriate value of type [org.springframework.beans.propertyeditors.CustomDateEditor]
Note that PropertyEditor are stateful, so you should not register instances directly.
Register property editor classes via customEditor property
Add PropertyEditorRegistrars via propertyEditorRegistrars property in CustomEditorConfigurer
As you want to configure the property editor instance, use property editor registrar instead.
<bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="propertyEditorRegistrars">
<list>
<bean class="org.example.CustomDateEditorRegistrar"/>
</list>
</property>
</bean>
As per the official documentation , the recommended way of registering a PropertyEditor is to create a class that implements propertyEditorRegistrar interface. Each propertyEditorRegistrar can register any number of propertyEditors on a given registry.
Two such implementaions are descibed below:
Approach 1: create a generalized class that implements PropertyEditorRegistrar.
This class can be used for any propertyEditor(s), so you can keep this class in your utils.
Lets name it CustomEditorRegistrar and it looks like this:
public class CustomEditorRegistrar implements PropertyEditorRegistrar
{
Class<?> t;
PropertyEditor propertyEditor;
public CustomEditorRegistrar(Class<?> t, PropertyEditor propertyEditor)
{
this.t = t;
this.propertyEditor = propertyEditor;
}
#Override
public void registerCustomEditors(PropertyEditorRegistry registry)
{
registry.registerCustomEditor(t, propertyEditor);
}
}
. The bean definition to register a CustomDateEditor is as below:
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="propertyEditorRegistrars">
<list>
<bean class="mky.spring.property.editor.date.CustomEditorRegistrar">
<constructor-arg index="0">
<value type="java.lang.Class">java.util.Date</value>
</constructor-arg>
<constructor-arg index="1">
<bean class="org.springframework.beans.propertyeditors.CustomDateEditor">
<constructor-arg index="0">
<bean class="java.text.SimpleDateFormat">
<constructor-arg value="dd-MM-yyyy" />
</bean>
</constructor-arg>
<constructor-arg index="1" value="true" />
</bean>
</constructor-arg>
</bean>
</list>
</property>
</bean>
<bean
name="Customer"
class="mky.spring.property.editor.date.Customer"
p:name="Customer 1"
p:address="CounterHills LA"
p:deliveryDate="12-11-2016"
p:issueDate="12-10-2016" />
Sys-out client:
public class TestGenericClient
{
ApplicationContext ctx;
public TestGenericClient()
{
ctx = new ClassPathXmlApplicationContext("genericPropertyEditorRegistrar-beans.xml");
}
public static void main(String[] args)
{
System.out.println(new TestGenericClient().ctx.getBean("Customer"));
}
}
And the output is this:
Name=Customer 1
Address=CounterHills LA
Issue Date=Wed Oct 12 00:00:00 GST 2016
deliveryDate=Sat Nov 12 00:00:00 GST 2016
Approach2: create a specific propertyEditorRegistrar eg, for Date
public class CustomDateEditorRegistrar implements PropertyEditorRegistrar
{
#Override
public void registerCustomEditors(PropertyEditorRegistry registry)
{
registry.registerCustomEditor(java.util.Date.class, new CustomDateEditor(new SimpleDateFormat("dd-MM-yyyyy"),true));
}
}
And the bean declaration for this specific CustomDateEditor is :
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="propertyEditorRegistrars">
<list>
<bean class="mky.spring.property.editor.date.CustomDateEditorRegistrar" />
</list>
</property>
</bean>
Sys-out cleint:
public TestDateClient()
{
ctx = new ClassPathXmlApplicationContext("datePropertyEditorRegistrar-beans.xml");
}
public static void main(String[] args)
{
System.out.println(new TestDateClient().ctx.getBean("Customer"));
}
And the same output :
Name=Customer 1
Address=CounterHills LA
Issue Date=Wed Oct 12 00:00:00 GST 2016
deliveryDate=Sat Nov 12 00:00:00 GST 2016

Having issues autowiring a sessionfactory bean with spring mvc and hibernate

I am trying to implement auto-wiring into my project, but it seems that my application isn't seeing my SessionFactory definition in my application-context.xml when I am running it.
I'm probably missing something really obvious, though I've tried several solutions from posts having similar issues with no success.
I am using Spring MVC and Hibernate.
Here is my application-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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:annotation-config />
<context:component-scan base-package="arlua" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="serverDatasource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>oracle.jdbc.driver.OracleDriver</value>
</property>
<property name="url">
<value>url</value>
</property>
<property name="username">
<value>${user}</value>
</property>
<property name="password">
<value>${pwd}</value>
</property>
</bean>
<bean id="propertyPlaceholderConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>
<bean id="mySessionFactory"
class="org.springframework.orm.hibernate3.annotation.LocalSessionFactoryBean">
<property name="mappingResources">
<list>
<value>mapping/user_info.hbm.xml</value>
<value>mapping/login.hbm.xml</value>
<value>mapping/linked_accounts.hbm.xml</value>
<value>mapping/application_instance.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="dataSource" ref="serverDatasource"/>
</bean>
<bean id = "userInfoDaoImpl" class="arlua.dao.impl.UserInfoDaoImpl">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
<bean id = "loginDaoImpl" class="arlua.dao.impl.LoginDaoImpl">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
<bean id = "linkedAccountsDaoImpl" class="arlua.dao.impl.LinkedAccountsDaoImpl">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
<!--
<bean id = "applicationInstanceDaoImpl" class="arlua.dao.impl.ApplicationInstanceDaoImpl">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
-->
<!-- ************* TRANSACTION MANAGEMENT USING AOP **************** -->
<bean id="myTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
<aop:config>
<aop:pointcut id="allMethods" expression="execution(* arlua.dao.TableEntityFetchDao.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="allMethods"/>
</aop:config>
<tx:advice id="txAdvice" transaction-manager="myTransactionManager">
<tx:attributes>
<tx:method name="saveEntity"
propagation = "REQUIRES_NEW"
isolation = "READ_COMMITTED"
rollback-for = "Exception"/>
<tx:method name="updateEntity"
propagation = "REQUIRES_NEW"
isolation = "READ_COMMITTED"
rollback-for = "Exception"/>
<tx:method name="getEntity"
propagation = "REQUIRES_NEW"
isolation = "READ_COMMITTED"
rollback-for = "Exception"/>
<tx:method name="getAllEntities"
propagation = "REQUIRES_NEW"
isolation = "READ_COMMITTED"
rollback-for = "Exception"/>
</tx:attributes>
</tx:advice>
</beans>
Here is the controller class where I am trying to autowire.
package arlua.controller;
import arlua.dao.TableEntityFetchDao;
import arlua.dao.impl.ApplicationInstanceDaoImpl;
import arlua.service.SearchCriteria;
import arlua.service.UserAction;
import arlua.tables.ApplicationInstanceTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
#Controller
#SessionAttributes
public class SearchAppController{
#Autowired public ApplicationInstanceDaoImpl applicationInstanceDaoImpl;
private String input;
private ApplicationInstanceTable oldApp, newApp;
#RequestMapping(value = "/search_app_instance", method = RequestMethod.POST)
public String mySearchMethod(#ModelAttribute("search_criteria") SearchCriteria search){
input = search.getInput();
if(input != null)
input = input.toUpperCase();
return "redirect:search_app_instance";
}
#RequestMapping("/search_app_instance")
public ModelAndView mySuccessMethod(){
ModelAndView model = new ModelAndView("search_app_instance");
//Check and Make sure that the app exists
//ApplicationContext factory =
// new ClassPathXmlApplicationContext("spring-namespace.xml");
//TableEntityFetchDao urd = (TableEntityFetchDao)factory.getBean("applicationInstanceDaoImpl");
try{
ApplicationInstanceTable app =
(ApplicationInstanceTable) applicationInstanceDaoImpl.getEntity(input);
oldApp = app;
//Load app data into table
model.addObject("app_id", app.getApplication_id());
model.addObject("name", app.getName());
model.addObject("default_exp_period", app.getDefault_expiration_period());
model.addObject("server", app.getServer());
model.addObject("description", app.getDescription());
model.addObject("active", app.getActive());
model.addObject("conn_string", app.getConn_string());
model.addObject("creation_date", app.getCreation_date().getTime());
model.addObject("error", "");
}
catch(Exception e){
if(input != null)
{
model.addObject("error", "Application could not be found.");
input = "";
}
}
return model;
}
#RequestMapping(value = "/app_actions", method = RequestMethod.POST)
public String userActionsMethod(#ModelAttribute("user_action") UserAction action,
#ModelAttribute("app_info") ApplicationInstanceTable app_info){
if(action.getAction().equals("update_info"))
{
newApp = app_info;
return "redirect:update_app_info";
}
return "redirect:search_app_instance";
}
#RequestMapping("/update_app_info")
public ModelAndView updateInfoMethod(){
ModelAndView model = new ModelAndView("search_app_instance");
ApplicationContext factory =
new ClassPathXmlApplicationContext("spring-namespace.xml");
TableEntityFetchDao urd = (TableEntityFetchDao)factory.getBean("applicationInstanceDaoImpl");
newApp.setApplication_id(oldApp.getApplication_id());
newApp.setCreation_date(oldApp.getCreation_date());
urd.updateEntity(newApp);
model.addObject("msg", "Application '" + newApp.getApplication_id() + "' modified successfully.");
return model;
}
}
ApplicationInstanceDaoImpl Class
package arlua.dao.impl;
import arlua.dao.TableEntityFetchDao;
import arlua.tables.ApplicationInstanceTable;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
#Repository("applicationInstanceDaoImpl")
public class ApplicationInstanceDaoImpl extends TableEntityFetchDao{
public SessionFactory mySessionFactory;
#Resource(name = "mySessionFactory")
public void setMySessionFactory(SessionFactory mySessionFactory){
this.mySessionFactory = mySessionFactory;
}
public void saveEntity(Object applicationInstance) {
this.mySessionFactory.getCurrentSession().save((ApplicationInstanceTable)applicationInstance);
}
public ApplicationInstanceTable getEntity(Object application_id) {
return (ApplicationInstanceTable)this.mySessionFactory.getCurrentSession().
get(ApplicationInstanceTable.class, (String)application_id);
}
public void updateEntity(Object applicationInstance) {
this.mySessionFactory.getCurrentSession().update((ApplicationInstanceTable)applicationInstance);
}
public void deleteEntity(Object applicationInstance) {
this.mySessionFactory.getCurrentSession().delete((ApplicationInstanceTable)applicationInstance);
}
public List<?> getAllEntities() {
return this.mySessionFactory.getCurrentSession().createQuery
("FROM application_instance").list();
}
}
TableEntityFetchDao class
package arlua.dao;
import java.util.List;
import org.hibernate.SessionFactory;
/*
This class will serve as a generic blueprint for all of the other data access implementation classes
that are used to perform basic CRUD operations on the arlua tables (ie UserInfoDaoImpl).
*/
public abstract class TableEntityFetchDao {
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory){
this.sessionFactory = sessionFactory;
}
public abstract void saveEntity(final Object entity);
public abstract Object getEntity(final Object key);
public abstract void updateEntity(final Object entity);
public abstract void deleteEntity(final Object entity);
public abstract List<?> getAllEntities();
}
Here is most of my stack trace.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'searchAppController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public arlua.dao.impl.ApplicationInstanceDaoImpl arlua.controller.SearchAppController.applicationInstanceDaoImpl; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'applicationInstanceDaoImpl': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mySessionFactory' is defined
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.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4206)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4705)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
at org.apache.catalina.core.StandardService.start(StandardService.java:525)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'searchAppController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public arlua.dao.impl.ApplicationInstanceDaoImpl arlua.controller.SearchAppController.applicationInstanceDaoImpl; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'applicationInstanceDaoImpl': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mySessionFactory' is defined
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java: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.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1075)
at org.springframework.web.servlet.handler.AbstractUrlHandlerMapping.registerHandler(AbstractUrlHandlerMapping.java:383)
at org.springframework.web.servlet.handler.AbstractUrlHandlerMapping.registerHandler(AbstractUrlHandlerMapping.java:362)
at org.springframework.web.servlet.handler.AbstractDetectingUrlHandlerMapping.detectHandlers(AbstractDetectingUrlHandlerMapping.java:82)
at org.springframework.web.servlet.handler.AbstractDetectingUrlHandlerMapping.initApplicationContext(AbstractDetectingUrlHandlerMapping.java:58)
at org.springframework.context.support.ApplicationObjectSupport.initApplicationContext(ApplicationObjectSupport.java:119)
at org.springframework.web.context.support.WebApplicationObjectSupport.initApplicationContext(WebApplicationObjectSupport.java:72)
at org.springframework.context.support.ApplicationObjectSupport.setApplicationContext(ApplicationObjectSupport.java:73)
at org.springframework.context.support.ApplicationContextAwareProcessor.invokeAwareInterfaces(ApplicationContextAwareProcessor.java:106)
at org.springframework.context.support.ApplicationContextAwareProcessor.postProcessBeforeInitialization(ApplicationContextAwareProcessor.java:85)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:394)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1413)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
... 26 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: public arlua.dao.impl.ApplicationInstanceDaoImpl arlua.controller.SearchAppController.applicationInstanceDaoImpl; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'applicationInstanceDaoImpl': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mySessionFactory' is defined
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:502)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:282)
... 46 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'applicationInstanceDaoImpl': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mySessionFactory' is defined
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:300)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java: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.findAutowireCandidates(DefaultListableBeanFactory.java:844)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:786)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:474)
... 48 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mySessionFactory' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:527)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1083)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:274)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:435)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:409)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:541)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:156)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:297)
... 59 more
Edit: I ended up fixing my problem by autowiring into the interface TableEntityFetchDao rather than the class that was implementing it, ApplicationInstanceDaoImpl.
So, this
#Autowired public ApplicationInstanceDaoImpl applicationInstanceDaoImpl;
Became this
#Autowired public TableEntityFetchDao applicationInstanceDao;
And that seemed to fix my problem.
Instead of:
#Resource(name = "mySessionFactory")
public void setMySessionFactory(SessionFactory mySessionFactory){
this.mySessionFactory = mySessionFactory;
}
Use:
#Autowired
private SessionFactory mySessionFactory;
EDIT
As of the bellow comment:
Not sure why method is not working but my guess is that the parent TableEntityFetchDao class has the setter of session factory, then ApplicationInstanceDaoImpl - child class overrides it and spring for some reason does not like it, if TableEntityFetchDao would be an interface, setter would be injected, as #Resource serves the same purpose as #Autowired difference is that #Resource allows to specify the name of the bean which is injected, and #Autowire allows you mark the bean as not required.
To get #Resource working I would try to remove setter method from the parent class. Either way it makes no sense of having it there as it is not used. Also sessionFactory field. This can be removed as well. Then class contains only abstract methods and can be made an interface. Also I would annotate TableEntityFetchDao with #Service annotation for better understanding that it is a service-layer class.
#Resource(name = "mySessionFactory")
public void setMySessionFactory(SessionFactory mySessionFactory){
this.mySessionFactory = mySessionFactory;
}
try as #Autowired
public void setMySessionFactory(SessionFactory mySessionFactory){
this.mySessionFactory = mySessionFactory;
}
modify your code from the below code snippet in your spring configuration file
<bean id="mySessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="mappingLocations">
<list>
<value>mapping/user_info.hbm.xml</value>
<value>mapping/login.hbm.xml</value>
<value>mapping/linked_accounts.hbm.xml</value>
<value>mapping/application_instance.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="dataSource" ref="serverDatasource"/>
I hope this code will work for you, and let me know , if still you are facing the problem

java.lang.IllegalArgumentException: 'sessionFactory' or 'hibernateTemplate' is required in spring+hibernate

I am doing spring + hibernate apllication. When I run the application on tomcat server I am getting some exception. Below is my code.
This is my bean config file.
<?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-2.5.xsd">
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>WEB-INF/database/db.properties</value>
</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 id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>Employee.hbm.xml</value>
</list>
</property>
</bean>
<bean id="employeeBo" class="com.saggezza.employee.bo.impl.EmployeeBoImpl">
<property name="employeeDao" ref="employeeDao" />
</bean>
<bean id="employeeDao" class="com.saggezza.employee.dao.impl.EmployeeDaoImpl">
<constructor-arg ref="sessionFactory"></constructor-arg>
</bean>
this is my dao class.
public class EmployeeDaoImpl extends HibernateDaoSupport implements EmployeeDao {
private SessionFactory sessionFactory;
public EmployeeDaoImpl(SessionFactory sessionfactory){
this.sessionFactory=sessionfactory;
}
#Override
public List<Employee> getEmployeeDetails() {
return getHibernateTemplate().find("from Employee");
}
}
Here another class employeeBo is calling the employeeDaoImpl.
when I run thisI am getting the below exception.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeBo' defined in ServletContext resource [/WEB-INF/spring/EmployeeBean.xml]: Cannot resolve reference to bean 'employeeDao' while setting bean property 'employeeDao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeDao' defined in ServletContext resource [/WEB-INF/spring/EmployeeBean.xml]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: 'sessionFactory' or 'hibernateTemplate' is required
Can anybody help to resolve this. I have tried a lot and google it as well.But did get the solution.
If you have two configuration files, you duplicates 'sessionFactory' definition. Remove one of the 'sessionFactory' definitions . You would have got duplicate bean definition exception before the IllegalArgumentException.
Edit: After your comment,
public class EmployeeDaoImpl extends HibernateDaoSupport implements EmployeeDao {
public EmployeeDaoImpl(SessionFactory sessionfactory){
setSessionFactory(sessionfactory);
}
#Override
public List<Employee> getEmployeeDetails() {
return getHibernateTemplate().find("from Employee");
}
}
or get rid of constructor in above code and inject 'sessionFactory' using setter injection.See org.springframework.orm.hibernate3.support.HibernateDaoSupport.setSessionFactory(SessionFactory). I prefer later approach.
I think the problem is the type of SessionFactory you are injecting in EmployeeDaoImpl does not match with the type of the SessionFactory you used in the class.
Can you check it?
This is an old question so must be solved now but still if someone comes across this problem. Following is solution.
You can use Hibernate DAO Support by extending HibernateDAOSupport class and overriding its afterPropertiesSet() method.
This method is called in HibernateDAO support and at that time since sessionFactory is null it is throwing this error. In your custom class you can set this property explicitly and then call the same method of Parent Class (i.e. HibernateDAOSupport's addProperties() method)
package com.techcielo.spring4.hibernate.template;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;
#Component("hibernateTemplate")
public class Hibernate4CustomTemplate extends HibernateTemplate{
#Autowired(required=true)
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
System.out.println("Setting SessionFactory");
this.sessionFactory = sessionFactory;
super.setSessionFactory(sessionFactory);
}
#Override
public void afterPropertiesSet() {
System.out.println("Checking if properties set..."+this.sessionFactory);
setSessionFactory(sessionFactory);
super.afterPropertiesSet();
}
}
Following can be used for sample!
I had the same problem and fix it by using Autowired constructor with EntityManagerFactory. Keyur answer is correct
#Service
class EmployeeDaoImpl #Autowired constructor(
factory: EntityManagerFactory
) : HibernateDaoSupport(), EmployeeDao {
init {
if (factory.unwrap(SessionFactory::class.java) == null) {
throw NullPointerException("factory is not a hibernate factory")
}
setSessionFactory(factory.unwrap(SessionFactory::class.java))
}
...
}

org.springframework.beans.factory.BeanCreationException: as well as org.springframework.beans.BeanInstantiationException

I tried to do login and some database manipulations(insert,delete) in spring and also help with jsp.I am totally new to spring.I am getting the following error like bean creation exception.I have defined dvd as servlet name in web.xml. So my dvd_servlet.xml file is as like below
<beans.................>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/DVD"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean name="DvdController" class="DvdController" >
<property name="dataSource" ref="dataSource"/>
</bean>
<bean name="LoginController" class="LoginController" >
<property name="dataSource" ref="dataSource"/>
</bean>
<bean name="AccountCreationController" class="AccountCreationController" >
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
my LoginController is like
public class LoginController implements Controller {
int check;
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource=dataSource;
}
public DataSource getDataSource() {
return dataSource;
}
JdbcTemplate jdbcTemplate=new JdbcTemplate(dataSource);
#RequestMapping(value="/Login",method=RequestMethod.POST)
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {
String userName = request.getParameter("userName");
String password=request.getParameter("password");
try {
String selectQuery=("SELECT * FROM USERDETAILS WHERE NAME='"+userName+"'AND PASSWORD='"+password+"'");
check=jdbcTemplate.update(selectQuery,new Object[]{});
System.out.println(check);
if(check!=0) {
response.sendRedirect("DvdController");
}
}
catch(IOException e) {
e.printStackTrace();
}
return new ModelAndView("failure");
}
My error is like as below:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'LoginController' defined in ServletContext resource [/WEB-INF/dvd-servlet.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [LoginController]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: Property 'dataSource' is required
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(support:AbstractAutowireCapableBeanFactory.java):965)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(support:AbstractAutowireCapableBeanFactory.java):911)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(support:AbstractAutowireCapableBeanFactory.java):485)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(support:AbstractAutowireCapableBeanFactory.java):456)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(support:AbstractBeanFactory.java):291)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(support:DefaultSingletonBeanRegistry.java):222)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(support:AbstractBeanFactory.java):288)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(support:AbstractBeanFactory.java):190)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(support:DefaultListableBeanFactory.java):580)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:442)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:458)
root cause
org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [LoginController]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: Property 'dataSource' is required
org.springframework.beans.BeanUtils.instantiateClass(beans:BeanUtils.java):141)
org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(support:SimpleInstantiationStrategy.java):74)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(support:AbstractAutowireCapableBeanFactory.java):958)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(support:AbstractAutowireCapableBeanFactory.java):911)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(support:AbstractAutowireCapableBeanFactory.java):485)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(support:AbstractAutowireCapableBeanFactory.java):456)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(support:AbstractBeanFactory.java):291)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(support:DefaultSingletonBeanRegistry.java):222)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(support:AbstractBeanFactory.java):288)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(support:AbstractBeanFactory.java):190)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(support:DefaultListableBeanFactory.java):580)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:442)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:458)
root cause
java.lang.IllegalArgumentException: Property 'dataSource' is required
org.springframework.jdbc.support.JdbcAccessor.afterPropertiesSet(support:JdbcAccessor.java):134)
org.springframework.jdbc.core.JdbcTemplate.(core:JdbcTemplate.java):164)
LoginController.(LoginController.java:29)
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
java.lang.reflect.Constructor.newInstance(Constructor.java:513)
org.springframework.beans.BeanUtils.instantiateClass(beans:BeanUtils.java):126)
org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(support:SimpleInstantiationStrategy.java):74)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(support:AbstractAutowireCapableBeanFactory.java):958)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(support:AbstractAutowireCapableBeanFactory.java):911)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(support:AbstractAutowireCapableBeanFactory.java):485)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(support:AbstractAutowireCapableBeanFactory.java):456)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(support:AbstractBeanFactory.java):291)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(support:DefaultSingletonBeanRegistry.java):222)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(support:AbstractBeanFactory.java):288)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(support:AbstractBeanFactory.java):190)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(support:DefaultListableBeanFactory.java):580)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:442)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:458)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:339)
please help me to clear this!!!
I see two issues here:
<bean name="LoginController" class="LoginController" >
<property name="dataSource" ref="dataSource"/>
</bean>
Is LoginController really the full qualified class name? It should be something like com.cy.LoginController
Second, Spring states that the constructor of the LoginController needs the property dataSource. It looks like the LoginController needs constructor injection of the dataSource, what you are doing is setter injection, so try this:
Instead of <property name="dataSource" ref="dataSource/>, write:
<constructor-arg ref="dataSource"/>

Resources