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

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

in your mvc-dispatcher-servlet.xml you misspelled the following: org.springframework.web.servlet.handeler.SimpleMappingExceptionResolver
handeler is written instead of handler

Related

How to create the bean class in spring?

I am creating bean class of JavaMailSender and autowired the javamailsender but i getting error
package com.websystique.springsecurity.service;
import java.util.List;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailParseException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.websystique.springsecurity.dao.EmployeeDao;
import com.websystique.springsecurity.model.Employee;
#Service
#Transactional
public class EmployeeServiceImpl implements EmployeeService {
#Autowired
private EmployeeDao employeeDAOImpl;
Employee Employee;
#Autowired
private JavaMailSender mailSender;
#Autowired
private SimpleMailMessage simpleMailMessage;
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
#Transactional
public void addEmployee(Employee employee) {
employeeDAOImpl.addEmployee(employee);
StringBuilder subject = new StringBuilder();
subject.append("User ");
subject.append(employee.getFirstname());
subject.append(" ");
subject.append(employee.getLastname());
subject.append(" has been added");
String content = subject.toString()+" Successfully!";
sendMail("", content,subject.toString(),employee.getEmail(),"D:\\log.pdf");
}
#Transactional
public List<Employee> getAllEmployees() {
return employeeDAOImpl.getAllEmployees();
}
#Transactional
public void deleteEmployee(Integer employeeId) {
employeeDAOImpl.deleteEmployee(employeeId);
}
#Transactional
public Employee getEmployee(int empid) {
return employeeDAOImpl.getEmployee(empid);
}
#Transactional
public Employee updateEmployee(Employee employee) {
Employee emp = employeeDAOImpl.updateEmployee(employee);
StringBuilder subject = new StringBuilder();
subject.append("User ");
subject.append(emp.getFirstname());
subject.append(" ");
subject.append(emp.getLastname());
subject.append(" has been updated");
String content = subject.toString()+" Successfully!";
sendMail("", content,subject.toString(),emp.getEmail(),"D:\\log.pdf");
return emp;
}
#Transactional
public void setEmployeeDAO(EmployeeDao employeeDAO) {
this.employeeDAOImpl = employeeDAO;
}
#Transactional
public void sendMail(String dear, String content,String subject,String
toEmail,String filePath) {
MimeMessage message = mailSender.createMimeMessage();
try{
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(new InternetAddress("saranpartneritech#gmail.com"));
helper.setTo(new InternetAddress(toEmail));
helper.setSubject(subject);
helper.setText(content);
if(filePath!=null){
FileSystemResource file = new FileSystemResource(filePath);
helper.addAttachment(file.getFilename(), file);
}
}catch (MessagingException e) {
throw new MailParseException(e);
}
mailSender.send(message);
}
}
I couldn't create the bean class for bean id="mailSender". i am working on it for past two days please get me out of it.
<context:component-scan base-
package="com.websystique.springsecurity.controller" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:resources mapping="/static/**" location="/static/" />
<mvc:annotation-driven conversion-service="conversionService"/>
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionService
FactoryBean">
<property name="converters">
<list>
<bean id="roleToUserProfile"
class="com.websystique.springsecurity.util.RoleToUserProfileConverter" />
</list>
</property>
</bean>
<bean id="mailSender"
class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.gmail.com" />
<property name="port" value="587" />
<property name="username" value="saranpartneritech#gmail.com" />
<property name="password" value="Saran2595" />
<property name="javaMailProperties">
<props>
<prop key="mail.transport.protocol">smtp</prop>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
</props>
</property>
</bean>
<!--
<bean id="mailMail" class="com.mkyong.common.MailMail">
<property name="mailSender" ref="mailSender" />
<property name="simpleMailMessage" ref="customeMailMessage" />
</bean>
<bean id="customeMailMessage"
class="org.springframework.mail.SimpleMailMessage">
<property name="from" value="saranpartneritech#gmail.com" />
<property name="subject" value="Customer Report" />
<property name="text">
<value>
<![CDATA[
Dear %s,
Mail Content : %s
]]>
</value>
</property>
</bean> -->
</beans>
And error page
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'employeeController': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: private
com.websystique.springsecurity.service.EmployeeService
com.websystique.springsecurity.controller.EmployeeController.employeeServiceImpl;
nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'employeeServiceImpl': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: private
org.springframework.mail.javamail.JavaMailSender
com.websystique.springsecurity.service.EmployeeServiceImpl.mailSender;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
[org.springframework.mail.javamail.JavaMailSender] found for
dependency: expected at least 1 bean which qualifies as autowire
candidate for this dependency. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
at
org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
at
org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
at
org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at
org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4853)
at
org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5314)
at
org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at
org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
at
org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
at java.util.concurrent.FutureTask.run(FutureTask.java:266) at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
your component scan includes only com.websystique.springsecurity.controller. So it will not be able to scan other packages to inject the dependencies. enable the component scan on top package(com.websystique.springsecurity) and override bean definations (if required) in xml file.
Try this in your xml and if it works revert back

How can I read multiple xml files from two different folders in Spring Batch?

I have multiple files to read and write from two different directories with same parent path.
Is it possible to select particular directory in "org.springframework.batch.item.file.MultiResourceItemReader" if one of the directory has no files to read?
<!-- multi xml reader -->
<bean id="multiResourceReader" class="org.springframework.batch.item.file.MultiResourceItemReader">
<property name="resources" ref="vinFeedFileResouce" />
<property name="delegate" ref="vinFeedReader" />
</bean>
<bean id="vinFeedFileResouce" class="org.springframework.core.io.FileSystemResource" scope="step">
<constructor-arg>
<list>
<ref bean="read_ONE" />
<ref bean="read_TWO" />
</list>
</constructor-arg>
</bean>
<bean id="read_ONE" class="org.springframework.core.io.FileSystemResource" scope="step">
<constructor-arg value="#{path_ONE}"></constructor-arg>
</bean>
<bean id="read_TWO" class="org.springframework.core.io.FileSystemResource" scope="step">
<constructor-arg value="#{path_TWO}"></constructor-arg>
</bean>
I am getting following error for reader:
[pool-1-thread-1](batch.listener.ModelMasterFailureListener:13)-Encountered error on Model master read
org.springframework.batch.item.ItemStreamException: Failed to initialize the reader
at org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader.open(AbstractItemCountingItemStreamItemReader.java:137)
at org.springframework.batch.item.file.MultiResourceItemReader.read(MultiResourceItemReader.java:105)
at org.springframework.batch.core.step.item.SimpleChunkProvider.doRead(SimpleChunkProvider.java:90)
at org.springframework.batch.core.step.item.FaultTolerantChunkProvider.read(FaultTolerantChunkProvider.java:87)
at org.springframework.batch.core.step.item.SimpleChunkProvider$1.doInIteration(SimpleChunkProvider.java:108)
at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:367)
at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:214)
at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:143)
at org.springframework.batch.core.step.item.SimpleChunkProvider.provide(SimpleChunkProvider.java:103)
at org.springframework.batch.core.step.item.ChunkOrientedTasklet.execute(ChunkOrientedTasklet.java:68)
at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:386)
at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:130)
at org.springframework.batch.core.step.tasklet.TaskletStep$2.doInChunkContext(TaskletStep.java:264)
at org.springframework.batch.core.scope.context.StepContextRepeatCallback.doInIteration(StepContextRepeatCallback.java:76)
at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:367)
at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:214)
at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:143)
at org.springframework.batch.core.step.tasklet.TaskletStep.doExecute(TaskletStep.java:250)
at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:195)
at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:135)
at org.springframework.batch.core.job.flow.JobFlowExecutor.executeStep(JobFlowExecutor.java:61)
at org.springframework.batch.core.job.flow.support.state.StepState.handle(StepState.java:60)
at org.springframework.batch.core.job.flow.support.SimpleFlow.resume(SimpleFlow.java:144)
at org.springframework.batch.core.job.flow.support.SimpleFlow.start(SimpleFlow.java:124)
at org.springframework.batch.core.job.flow.FlowJob.doExecute(FlowJob.java:135)
at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:281)
at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:120)
at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:48)
at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:114)
at com.ahm.ngt.cbo.feed.batch.scheduler.RunScheduler.run(RunScheduler.java:80)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.util.MethodInvoker.invoke(MethodInvoker.java:273)
at org.springframework.scheduling.support.MethodInvokingRunnable.run(MethodInvokingRunnable.java:65)
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:51)
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:98)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:206)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
at java.lang.Thread.run(Thread.java:662)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'scopedTarget.vinFeedFileResouce' defined in class path resource [spring/batch/jobs/ca-vin-feed-config.xml]: Unsatisfied dependency expressed through constructor argument with index 0 of type [java.io.File]: Could not convert constructor argument value of type [java.util.ArrayList] to required type [java.io.File]: Failed to convert value of type 'java.util.ArrayList' to required type 'java.io.File'; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type [java.util.ArrayList] to required type [java.io.File]: PropertyEditor [org.springframework.beans.propertyeditors.FileEditor] returned inappropriate value
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:702)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:196)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1003)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:907)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$2.getObject(AbstractBeanFactory.java:329)
at org.springframework.batch.core.scope.StepScope.get(StepScope.java:150)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:325)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:33)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:184)
at com.sun.proxy.$Proxy1.exists(Unknown Source)
at org.springframework.batch.item.xml.StaxEventItemReader.doOpen(StaxEventItemReader.java:187)
at org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader.open(AbstractItemCountingItemStreamItemReader.java:134)
... 45 more
If you see the source code of FileSystemResource, you would find the constructor can take either File or String not list of files or String. You can write custom Resource Reader to read the files from multiple directory. Here is an example
<bean id="multiResourceReader" class="org.springframework.batch.item.file.MultiResourceItemReader">
<property name="resources" value="#{myResourceReader.read()}" />
<property name="delegate" ref="vinFeedReader" />
</bean>
<bean id="myResourceReader" class="com.kp.swasthik.MyResourceReader">
<property name="resource" value="file:///path1/*.txt, file:///path2/*.txt"></property>
</bean>
The ResourceReader class.
public class MyResourceReader {
private String resource;
public String getResource() {
return resource;
}
public void setResource(String resource) {
this.resource = resource;
}
public Resource[] read(){
List<Resource> resources = new ArrayList<>();
if(resource == null || resource.isEmpty()){
return new Resource[]{};
}
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Arrays.stream(resource.split(",")).forEach(v->{
try {
Collections.addAll(resources, resolver.getResources(v));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
});
return resources.toArray(new Resource[0]);
}
}
Switch to annotation based configuration. There you could add all your resources (from different dirs) to the reader:
#Bean
public ItemReader<?> reader() {
Resource[] res = ... //get eg using PathMatchingResourcePatternResolver multiple times on different dirs
MultiResourceItemReader<?> r = new MultiResourceItemReader<>();
r.setResources(res);
return r;
}

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

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

Spring Batch - MongoDB to XML - Caused by: java.lang.IllegalStateException: A type to convert the input into is required

I am developing Spring Batch - MongoDB to XML example. In this example, when I run the main method I see the below error is cominng. Please guide on the below error. I tried to find the solution on the web, but I dont find anything helpful on the web yet.
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'step1': Cannot resolve reference to bean 'mongodbItemReader' while setting bean property 'itemReader'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongodbItemReader' defined in class path resource [job-report.xml]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: A type to convert the input into is required.
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:1492)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1237)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:552)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:740)
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:93)
at com.mkyong.App.main(App.java:15)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongodbItemReader' defined in class path resource [job-report.xml]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: A type to convert the input into is required.
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1589)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:554)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351)
... 15 more
Caused by: java.lang.IllegalStateException: A type to convert the input into is required.
at org.springframework.util.Assert.state(Assert.java:392)
at org.springframework.batch.item.data.MongoItemReader.afterPropertiesSet(MongoItemReader.java:200)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1648)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1585)
... 22 more
database.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
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.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo.xsd">
<!-- connect to mongodb -->
<mongo:mongo host="127.0.0.1" port="27017" />
<mongo:db-factory dbname="yourdb" />
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>
</beans>
context.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.xsd">
<bean id="transactionManager" class="org.springframework.batch.support.transaction.ResourcelessTransactionManager"/>
<!-- stored job-meta in memory -->
<bean id="jobRepository" class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
<property name="transactionManager" ref="transactionManager" />
</bean>
<bean id="jobLauncher" class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="jobRepository" ref="jobRepository" />
</bean>
</beans>
job-report.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:batch="http://www.springframework.org/schema/batch" xmlns:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util" 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.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<batch:job id="reportJob">
<batch:step id="step1">
<batch:tasklet>
<batch:chunk reader="mongodbItemReader" writer="xmlItemWriter" commit-interval="1">
</batch:chunk>
</batch:tasklet>
</batch:step>
</batch:job>
<bean id="mongodbItemReader" class="org.springframework.batch.item.data.MongoItemReader">
<property name="template" ref="mongoTemplate" />
<property name="collection" value="report" />
</bean>
<bean id="xmlItemWriter" class="org.springframework.batch.item.xml.StaxEventItemWriter">
<property name="resource" value="classpath:xml/report.xml" />
<property name="marshaller" ref="reportMarshaller" />
<property name="rootTagName" value="record" />
</bean>
<!-- ==== Solution-1 ==== -->
<bean id="reportMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<value>com.mkyong.Report</value>
</property>
</bean>
<!-- ==== Solution-2 ==== -->
<!-- <bean id="reportMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller">
<property name="aliases">
<util:map id="aliases">
<entry key="record" value="com.mkyong.Report" />
</util:map>
</property>
<property name="converters">
<array>
<ref bean="reportConverter" />
</array>
</property>
</bean> -->
<bean id="reportConverter" class="com.mkyong.ReportConverter" />
</beans>
Repoer.java
#XmlRootElement(name = "record")
public class Report {
private int id;
private Date date;
private long impression;
private int clicks;
private BigDecimal earning;
#XmlAttribute(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#XmlElement(name = "date")
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
#XmlElement(name = "impression")
public long getImpression() {
return impression;
}
public void setImpression(long impression) {
this.impression = impression;
}
#XmlElement(name = "clicks")
public int getClicks() {
return clicks;
}
public void setClicks(int clicks) {
this.clicks = clicks;
}
#XmlElement(name = "earning")
public BigDecimal getEarning() {
return earning;
}
public void setEarning(BigDecimal earning) {
this.earning = earning;
}
}
App.java
public class App {
public static void main(String[] args) {
String[] springConfig = { "database.xml", "context.xml", "job-report.xml" };
ApplicationContext context = new ClassPathXmlApplicationContext(springConfig);
JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
Job job = (Job) context.getBean("reportJob");
try {
JobExecution execution = jobLauncher.run(job, new JobParameters());
System.out.println("Exit Status : " + execution.getStatus());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Done");
}
}
Could you help on this?
As the error points out, you need to set the "type" property on your "mongodbItemReader" bean.
See MongoItemReader javadoc.
Example:
<bean id="mongodbItemReader" class="org.springframework.batch.item.data.MongoItemReader">
<property name="template" ref="mongoTemplate" />
<property name="collection" value="report" />
<property name="targetType" value="Report.class" />
</bean>
You might need to specify the package name in the value (I haven't tried it).
Thank you #Sergio, it was great help from you, but below configuration works.
<bean id="mongodbItemReader" class="org.springframework.batch.item.data.MongoItemReader">
<property name="template" ref="mongoTemplate" />
<property name="collection" value="report" />
<property name="targetType" value="com.mkyong.model.Report" />
<property name="query" value="{'_id':{$gt:0} }" />
<property name="sort">
<util:map>
<entry key="id" value="#{T(org.springframework.data.domain.Sort.Direction).ASC}" />
</util:map>
</property>
</bean>
The only problem I see, nothing is getting write into the XML file. I will raise a separate question for this issue.
Note: The main reason of this error is you need to set <property name="targetType" value="com.mkyong.model.Report" /> this property correctly.
You can also refer: http://www.mkyong.com/spring-batch/how-to-convert-date-in-beanwrapperfieldsetmapper/ as another solution.

Spring-Mvc - JdbcDaoSupport Error

I am getting the following error:
[C:\Users\Darin\apache-tomcat-6.0\webapps\crimeTrack\WEB-INF\classes\com\crimetrack\jdbc\JdbcCountryDAO.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: 'dataSource' or 'jdbcTemplate' is required
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1455)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:631)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:588)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:645)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:508)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:449)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:133)
at javax.servlet.GenericServlet.init(GenericServlet.java:212)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1206)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1026)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4421)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4734)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:799)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:779)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:601)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:943)
at org.apache.catalina.startup.HostConfig.deployWARs(HostConfig.java:778)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:504)
at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1385)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:306)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:142)
at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1389)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1653)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1662)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1642)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalArgumentException: 'dataSource' or 'jdbcTemplate' is required
jdbcDAOCountry.java
#Repository
public class JdbcCountryDAO extends JdbcDaoSupport implements CountryDAO{
private final Logger logger = Logger.getLogger(getClass());
#Autowired
private JdbcTemplate jdbcTemplate;
public List<Country> getCountryList() {
int countryId = 6;
String countryCode = "AI";
logger.debug("In getCountryList()");
String sql = "SELECT * FROM TBLCOUNTRY WHERE countryId = ? AND countryCode = ?";
logger.debug("Executing getCountryList String "+sql);
Object[] parameters = new Object[] {countryId, countryCode};
logger.info(sql);
//List<Country> countryList = getJdbcTemplate().query(sql,new CountryMapper());
List<Country> countryList = getJdbcTemplate().query(sql, parameters,new CountryMapper());
return countryList;
}
public void saveCountry(Country country) {
logger.debug("In saveCountry");
String sql= "INSERT INTO crimetrack.tblcountry (countryName, countryCode) " +
"VALUES (:countryName, :countryCode)";
logger.debug("Executing saveCountry String " + sql);
int count = getJdbcTemplate().update(sql,new MapSqlParameterSource()
.addValue("countryName", country.getCountryName())
.addValue("countryCode", country.getCountryCode()));
logger.debug(count +" Rows affected in tblCountry");
}
public void updateCountry(Country country) {
logger.debug("In updateCountry");
String sql= "UPDATE crimetrack.tblcountry SET countryName = :countryName, "+
"countryCode = :countryCode WHERE countryId = :countryId";
logger.debug("Executing updateCountry String " + sql);
int count = getJdbcTemplate().update(sql,new MapSqlParameterSource()
.addValue("countryId",country.getCountryId())
.addValue("countryName", country.getCountryName())
.addValue("countryCode", country.getCountryCode()));
logger.debug(count +" Rows affected in tblCountry");
}
public static class CountryMapper implements ParameterizedRowMapper<Country>{
public Country mapRow(ResultSet rs, int rowNum) throws SQLException {
Country country = new Country();
country.setCountryCode(rs.getString("countryCode"));
country.setCountryId(rs.getInt("countryId"));
country.setCountryName(rs.getString("countryName"));
return country;
}
}
}
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: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/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- __________________________________________________________________________________________________ -->
<bean id="countryManager" class="com.crimetrack.service.CountryManager">
<property name="countryDao" ref="countryDao"/>
</bean>
<bean id="countryDao" class="com.crimetrack.jdbc.JdbcCountryDAO">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- __________________________________________________________________________________________________ -->
<bean id="authenticationManager" class="com.crimetrack.service.AuthenticationManager">
<property name="loginDao" ref="loginDao" />
</bean>
<bean id="loginDao" class="com.crimetrack.jdbc.JdbcLoginDAO">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- __________________________________________________________________________________________________ -->
<bean id="divisionManager" class="com.crimetrack.service.DivisionManager">
<property name="divisionDao" ref="divisionDao"/>
</bean>
<bean id="divisionDao" class="com.crimetrack.jdbc.JdbcDivisionDAO">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- __________________________________________________________________________________________________ -->
<bean id="positionManager" class="com.crimetrack.service.PositionManager">
<property name="positionDao" ref="positionDao"/>
</bean>
<bean id="positionDao" class="com.crimetrack.jdbc.JdbcPositionDAO">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- __________________________________________________________________________________________________ -->
<bean id="genderManager" class="com.crimetrack.service.GenderManager">
<property name="genderDao" ref="genderDao"/>
</bean>
<bean id="genderDao" class="com.crimetrack.jdbc.JdbcGenderDAO" >
<property name="dataSource" ref="dataSource" />
</bean>
<!-- __________________________________________________________________________________________________ -->
<bean id="officerRegistrationValidation" class="com.crimetrack.service.OfficerRegistrationValidation">
<property name="validateUserNameManager" ref="validateUserNameManager"/>
</bean>
<bean id="validateUserNameManager" class="com.crimetrack.service.ValidateUserNameManager">
<property name="officerDao" ref="officerDao"/>
</bean>
<bean id="officerDao" class="com.crimetrack.jdbc.JdbcOfficersDAO" >
<property name="dataSource" ref="dataSource" />
</bean>
<!-- __________________________________________________________________________________________________ -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource"><ref bean="dataSource" /></property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<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="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
<!-- __________________________________________________________________________________________________ -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans/spring-context-3.0.xsd">
<!-- __________________________________________________________________________________________________ -->
<!-- Supports annotations and allows the use of #Controller, #Required, #RequestMapping -->
<context:annotation-config/>
<context:component-scan base-package="com.crimetrack.jdbc"/>
<context:component-scan base-package="com.crimetrack.service"/>
<context:component-scan base-package="com.crimetrack.web" />
<mvc:annotation-driven />
Ensure the applicationContext.xml has the bean dataSource defined.
The DAO should pass a constructor-arg and not a property since dataSource is a constructor-arg.
Annotate a constructor method and ensure it accepts a dataSource.
The dataSource passes is the same one defined in the applicationContext.xml:
<bean id="countryDao" class="com.crimetrack.jdbc.JdbcCountryDAO">
<constructor-arg index="0" ref="dataSource"/>
</bean>
#Repository
public class JdbcCountryDAO extends JdbcDaoSupport implements CountryDAO {
private final Logger logger = Logger.getLogger(getClass());
#Autowired
JdbcCountryDAO(DataSource dataSource) {
setDataSource(dataSource);
}
public List<Country> getCountryList() {
// ...
The error is that no dataSource or jdbcTemplate is wired into the JdbcCountryDao bean:
java.lang.IllegalArgumentException: 'dataSource' or 'jdbcTemplate' is required
However your XML config shows that you have the dataSource sent, so are you sure that this error occurs when using the posted version of the file?
Also, there is no need to have declare a #Autowired jdbcTemplate in a class that extends JdbcDaoSupport as the superclass provides this for you already.

Categories