I'm trying to create a Spring Project with CRUD operation. I'm new to Spring, So I need a bit of help-
I'm getting a following error on submitting the form with post method-
Caused by: org.springframework.beans.NotWritablePropertyException:
Invalid property 'userDao' of bean class
[com.cjc.service.RegistrationServiceImpl]: Bean property 'userDao' 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.createNotWritablePropertyException(BeanWrapperImpl.java:231)
at
org.springframework.beans.AbstractNestablePropertyAccessor.setPropertyValue(AbstractNestablePropertyAccessor.java:423)
at
org.springframework.beans.AbstractNestablePropertyAccessor.setPropertyValue(AbstractNestablePropertyAccessor.java:280)
at
org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:95)
at
org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:75)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1514)
... 47 more
Jan 23, 2019 9:01:09 AM org.apache.catalina.core.StandardWrapperValve
invoke SEVERE: Allocate exception for servlet spring
org.springframework.beans.NotWritablePropertyException: Invalid
property 'userDao' of bean class
[com.cjc.service.RegistrationServiceImpl]: Bean property 'userDao' 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.createNotWritablePropertyException(BeanWrapperImpl.java:231)
at
org.springframework.beans.AbstractNestablePropertyAccessor.setPropertyValue(AbstractNestablePropertyAccessor.java:423)
at
org.springframework.beans.AbstractNestablePropertyAccessor.setPropertyValue(AbstractNestablePropertyAccessor.java:280)
at
org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:95)
at
org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:75)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1514)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1226)
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.findAutowireCandidates(DefaultListableBeanFactory.java:1192)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1116)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:543)
at
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
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)
Please find below the java files for the same-
Controller-
package com.cjc.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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 com.cjc.model.User;
import com.cjc.service.RegistrationService;
#Controller
public class RegistrationController {
#Qualifier("regservice")
private RegistrationService registrationService;
public void setRegistrationService(RegistrationService registrationService) {
this.registrationService = registrationService;
}
#RequestMapping(value="/registration", method=RequestMethod.POST)
public String Registration(#ModelAttribute User u) {
registrationService.addPerson(u);
return "RegSuccess";
}
}
Service-
package com.cjc.service;
import com.cjc.dao.UserDAO;
import com.cjc.model.User;
public class RegistrationServiceImpl implements RegistrationService {
private UserDAO userDao ;
public void setUserDao(UserDAO userDao) {
this.userDao = userDao;
}
#Override
public int addPerson(User u) {
// TODO Auto-generated method stub
return 0;
}
}
DAO Impl-
package com.cjc.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.cjc.model.User;
import com.cjc.util.HibernateUtil;
public class UserDaoImpl implements UserDAO{
#Override
public void addUser(User u) {
// TODO Auto-generated method stub
SessionFactory sessionFactory=HibernateUtil.getSessionFactory();
Session session=sessionFactory.openSession();
Transaction transaction=session.beginTransaction();
session.save(u);
transaction.commit();
}
#Override
public void deleteUser(int id) {
// TODO Auto-generated method stub
}
#Override
public List<User> getAllUser() {
// TODO Auto-generated method stub
return null;
}
#Override
public User getUserById(int id) {
// TODO Auto-generated method stub
return null;
}
#Override
public void updteUser(User u, int id) {
// TODO Auto-generated method stub
}
}
Spring-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" 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
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.cjc.controller" />
<bean id="userDAO" class="com.cjc.dao.UserDaoImpl">
</bean>
<bean id="regservice" class="com.cjc.service.RegistrationServiceImpl">
<property name="userDao" ref="userDAO"></property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames" value="application" />
</bean>
</beans>
Please help me in resolving the issue
You missing setter and getter in User Model. Add setter and getter.
Add getter in RegistrationServiceImpl class for UserDao:
public UserDAO getUserDao() {
return userDao;
}
Related
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>
I'm creating a Spring MVC Maven module based project so I have divided every layer into a maven module. When I try to run a basic site, code compiles fine but I get the error:
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'addressController' defined in file [C:\Program Files\Apache Software Foundation\Tomcat 8.0\wtpwebapps\croz-web\WEB-INF\classes\hr\croz\bspoljaric\controller\AddressController.class]: Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect bean class [hr.croz.bspoljaric.controller.AddressController] for resource metadata: could not find class that it depends on
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:525)
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:759)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4851)
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(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalStateException: Failed to introspect bean class [hr.croz.bspoljaric.controller.AddressController] for resource metadata: could not find class that it depends on
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.findResourceMetadata(CommonAnnotationBeanPostProcessor.java:344)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessMergedBeanDefinition(CommonAnnotationBeanPostProcessor.java:297)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors(AbstractAutowireCapableBeanFactory.java:953)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:522)
... 20 more
Caused by: java.lang.NoClassDefFoundError: Lhr/croz/bspoljaric/service/AddressService;
at java.lang.Class.getDeclaredFields0(Native Method)
at java.lang.Class.privateGetDeclaredFields(Unknown Source)
at java.lang.Class.getDeclaredFields(Unknown Source)
at org.springframework.util.ReflectionUtils.getDeclaredFields(ReflectionUtils.java:715)
at org.springframework.util.ReflectionUtils.doWithLocalFields(ReflectionUtils.java:656)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.buildResourceMetadata(CommonAnnotationBeanPostProcessor.java:361)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.findResourceMetadata(CommonAnnotationBeanPostProcessor.java:340)
... 23 more
Caused by: java.lang.ClassNotFoundException: hr.croz.bspoljaric.service.AddressService
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1333)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1167)
... 30 more
AddressDao.java
package hr.croz.bspoljaric.dao;
import java.util.List;
import hr.croz.bspoljaric.entity.Address;
public interface AddressDAO {
public void save(Address address);
public void delete(int addressID);
public Address get(int contactId);
public List<Address> getAll();
}
AddressDaoImpl.java
import java.util.List;
import org.springframework.stereotype.Repository;
import hr.croz.bspoljaric.dao.AddressDAO;
import hr.croz.bspoljaric.entity.Address;
#Repository
public class AddressDAOImpl implements AddressDAO{
#Override
public void save(Address address) {
// TODO Auto-generated method stub
}
#Override
public void delete(int addressID) {
// TODO Auto-generated method stub
}
#Override
public Address get(int contactId) {
// TODO Auto-generated method stub
return null;
}
#Override
public List<Address> getAll() {
List<Address> as = new ArrayList<>();
Address a = new Address();
a.setId(1l);
a.setStreet("MAKSIMIRSKA");
a.setStreetNo("2");
a.setCity(null);
as.add(a);
System.out.println("TEST: " + as.get(1));
return as;
}
}
AddressService.java
package hr.croz.bspoljaric.service;
import java.util.List;
import hr.croz.bspoljaric.entity.Address;
public interface AddressService {
public List<Address> getAll();
}
AddressServiceImpl.java
package hr.croz.bspoljaric.serviceimpl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import hr.croz.bspoljaric.dao.AddressDAO;
import hr.croz.bspoljaric.entity.Address;
import hr.croz.bspoljaric.service.AddressService;
#Service
public class AddressServiceImpl implements AddressService {
#Autowired
AddressDAO dao;
public List<Address> getAll() {
return dao.getAll();
}
}
AddressController.java
package hr.croz.bspoljaric.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import hr.croz.bspoljaric.service.AddressService;
#Controller
#RequestMapping("/test")
public class AddressController {
#Autowired
AddressService ads;
#RequestMapping(value = "/getAll", method = RequestMethod.GET)
public String getAllAddresses(Model model)
{
model.addAttribute("addresses", ads.getAll());
System.out.println("TEST!");
return "addressesListDisplay";
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>Croz Web Application</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context/
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="hr.croz.bspoljaric" />
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
Project view(all except web module):
https://imgur.com/a/mgBpd
Project view(web module):
https://imgur.com/a/4gtp8)
You need to mvn clean install in parent module to install the other module to local repo before you run your web module alone.
Or you can mvn clean install -am in web module, so that it will build the depended modules.
Please change the packaging to jar in service module, or just remove it, the default packaging is jar.
<packaging>jar</packaging>
<name>croz-service</name>
Go to the folder which contains the project pom file. Then get the cmd and run
mvn clean install
If it is failed, try it after deleting the target folder
I am trying to write spring application which is annotation configured. I have defined a dataSource and jdbcTemplate and i am sure that spring initializes them (when commented them i have an exception which tells me that this beans are not initialized). I have no idea why i have this exception when beans are initialize. I will copy xml, dao class and stacktrace.
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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg>
<ref bean="dataSource" />
</constructor-arg>
</bean>
</beans>
dao
#Repository
public class DomainsDao extends JdbcDaoSupport {
#Autowired
private MessageSourceAccessor msa;
#Autowired
private JdbcTemplate jdbcTemplate;
public List<Domain> getInactiveDomains() {
return jdbcTemplate.query(msa.getMessage("sql.pass.domain.select_inactive"), new DomainRowMapper());
}
public int getDomainId(String name) {
String sql = msa.getMessage("sql.pass.domain.select_by_name");
Object[] args = new Object[] { name };
return jdbcTemplate.queryForObject(sql, args, Integer.class);
}
}
stack trace
java.lang.IllegalArgumentException: 'dataSource' or 'jdbcTemplate' is required
org.springframework.jdbc.core.support.JdbcDaoSupport.checkDaoConfig(JdbcDaoSupport.java:111)
org.springframework.dao.support.DaoSupport.afterPropertiesSet(DaoSupport.java:44)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1631)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1568)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1120)
org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1044)
org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1208)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1120)
org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1044)
org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1208)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:667)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:633)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:681)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:552)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:493)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:521)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)
EDIT i will add all of my configuration
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<description>
SaaS Admin
</description>
<display-name>SaaS Admin</display-name>
<!-- <error-page> <error-code>404</error-code> <location>/error404.jsp</location>
</error-page> -->
<servlet>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/conf/app-config.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
app-config.xml
<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:task="http://www.springframework.org/schema/task"
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/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<!-- Scanning package with configuration files -->
<context:component-scan base-package="bg.abv.saas.admin.config" />
<!-- Application Message Bundle -->
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>WEB-INF/props/configure</value>
<value>WEB-INF/props/sql</value>
<value>WEB-INF/props/strings</value>
<value>WEB-INF/props/log4j</value>
</list>
</property>
<property name="defaultEncoding" value="UTF-8" />
<property name="cacheSeconds" value="60" />
</bean>
<bean id="msa"
class="org.springframework.context.support.MessageSourceAccessor">
<constructor-arg>
<ref bean="messageSource" />
</constructor-arg>
</bean>
WebServletApplicationInitializer
#EnableWebMvc
#Configuration
#ComponentScan("bg.abv")
#ImportResource(value = { "/WEB-INF/conf/data-source.xml" })
public class WebServletApplicationInitializer extends WebMvcConfigurerAdapter {
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/jsp/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/*");
}
data-source.xml the content of this file is the xml file with dataSource and jdbcTemplate beans.
I think you should drop the autowiring of jdbcTemplate in your DomainsDao and inject your dataSource instead. Then get the jdbcTemplate by calling the org.springframework.jdbc.core.support.JdbcDaoSupport#getJdbcTemplate method.
example:
#Repository
public class DomainsDao extends JdbcDaoSupport {
#Autowired
private MessageSourceAccessor msa;
#Autowired
public void setDs(DataSource dataSource) {
setDataSource(dataSource);
}
public List<Domain> getInactiveDomains() {
return getJdbcTemplate().query(msa.getMessage("sql.pass.domain.select_inactive"), new DomainRowMapper());
}
public int getDomainId(String name) {
String sql = msa.getMessage("sql.pass.domain.select_by_name");
Object[] args = new Object[] { name };
return getJdbcTemplate().queryForObject(sql, args, Integer.class);
}
}
If you still want to inject your own jdbcTemplate a similar approach is required:
#Repository
public class DomainsDao extends JdbcDaoSupport {
#Autowired
private MessageSourceAccessor msa;
#Autowired
public void setJT(JdbcTemplate jdbcTemplate) {
setJdbcTemplate(jdbcTemplate);
}
public List<Domain> getInactiveDomains() {
return getJdbcTemplate().query(msa.getMessage("sql.pass.domain.select_inactive"), new DomainRowMapper());
}
public int getDomainId(String name) {
String sql = msa.getMessage("sql.pass.domain.select_by_name");
Object[] args = new Object[] { name };
return getJdbcTemplate().queryForObject(sql, args, Integer.class);
}
}
The problem is that the JdbcDaoSupport class that you are inheriting from already has a jdbcTemplate property that you need to set. The JdbcDaoSupport checks whether you have provided either the jdbcTemplate or dataSource property in its afterPropertiesSet method. However you are declaring and injecting your own jdbcTemplate meaning DomainsDao has two jdbcTemplate properties (one you declare plus one inherited from JdbcDaoSupport)
You can solve this by removing the extends JdbcDaoSupport part from your calss declaration.
Alternatively if you really want to inherit from JdbcDaoSupport then change your class as follows
#Repository
public class DomainsDao extends JdbcDaoSupport {
#Autowired
private MessageSourceAccessor msa;
#Autowired
public DomainsDao (JdbcTemplate jdbcTemplate){
setJdbcTemplate(jdbcTemplate);
}
public List<Domain> getInactiveDomains() {
return getJdbcTemplate().query(msa.getMessage("sql.pass.domain.select_inactive"), new DomainRowMapper());
}
public int getDomainId(String name) {
String sql = msa.getMessage("sql.pass.domain.select_by_name");
Object[] args = new Object[] { name };
return getJdbcTemplate.queryForObject(sql, args, Integer.class);
}
}
Can you please try this,
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
I'm new in Spring and I'm try to create a simple quick start application.
My application is composed by three java classes, the pom.xml file and another xml file:
Produttore.java:
package com.mkyong.core;
import org.springframework.stereotype.Component;
#Component
public class Produttore {
private int iD;
private String ruolo;
public int getiD() {
return iD;
}
public void setiD(int iD) {
this.iD = iD;
}
public String getRuolo() {
return ruolo;
}
public void setRuolo(String ruolo) {
this.ruolo = ruolo;
}
#Override
public String toString(){
return "Produttore " + iD + ", ruolo " + ruolo;
}
}
Team.java:
package com.mkyong.core;
import java.util.List;
import org.springframework.stereotype.Component;
#Component
public class Team {
private Produttore Leader;
private List<Produttore> membri;
public Produttore getLeader() {
return Leader;
}
public void setLeader(Produttore leader) {
Leader = leader;
}
public List<Produttore> getMembri() {
return membri;
}
public void setMembri(List<Produttore> membri) {
this.membri = membri;
}
public void addMembri(Produttore p){
this.membri.add(p);
}
#Override
public String toString(){
return "Trainer " + Leader + " numero membri: " + membri.size();
}
}
test1.java:
package com.mkyong.core;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class test1 {
public static void main(String[] args){
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"Test1xml.xml"});
Team ris=(Team)context.getBean("TeamBean");
System.out.println(ris);
}
}
Test1xml.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-2.5.xsd">
<bean id="ProduttoreBean" class="com.mkyong.core.Produttore">
<property name="iD" value="1234"/>
<property name="ruolo" value="Trainer"/>
</bean>
<bean id="TeamBean" class="com.mkyong.core.Team">
<property name="Leader">
<bean class="com.mkyong.core.Produttore">
<property name="iD" value="1111"></property>
<property name="ruolo" value="Trainer"/>
</bean>
</property>
<property name="membri">
<util:list list-class="java.util.ArrayList">
<value>0</value>
<ref bean="ProduttoreBean2" />
</util:list>
</property>
</bean>
<bean id="ProduttoreBean2" class="com.mkyong.core.Produttore">
<property name="iD" value="1112" />
<property name="ruolo" value="Junior"/>
</bean>
</beans>
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mkyong.core</groupId>
<artifactId>Spring3Example</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>Spring3Example</name>
<url>http://maven.apache.org</url>
<properties>
<spring.version>3.0.5.RELEASE</spring.version>
</properties>
<dependencies>
<!-- Spring 3 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
</project>
I don't know why, but when I try to lunch the application it fails. I post the error:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'TeamBean' defined in class path resource [Test1xml.xml]: Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.util.ArrayList' to required type 'java.util.List' for property 'membri'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.mkyong.core.Produttore] for property 'membri[0]': no matching editors or conversion strategy found
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
at com.mkyong.core.test1.main(test1.java:8)
Caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.util.ArrayList' to required type 'java.util.List' for property 'membri'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.mkyong.core.Produttore] for property 'membri[0]': no matching editors or conversion strategy found
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:462)
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:499)
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:493)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1371)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1330)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1086)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
... 11 more
Caused by: java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.mkyong.core.Produttore] for property 'membri[0]': no matching editors or conversion strategy found
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:231)
at org.springframework.beans.TypeConverterDelegate.convertToTypedCollection(TypeConverterDelegate.java:520)
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:173)
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:447)
... 17 more
Could someone help me? Thanks a lot
convert value of type [java.lang.String] to required type [com.mkyong.core.Produttore] for property 'membri[0]' : This tells the Spring is unable to convert the String value at first position in arrayList to type Produttore. See the Explanation below :-
private List<Produttore> membri;
The error is because of above line. Because here you are defining that the arraylist with name membri will contain the objects of type Produttore but putting a String value at first position in it in xml i.e. 0:
<util:list list-class="java.util.ArrayList" value- type="com.mkyong.core.Produttore">
*<value>0</value>*
<ref bean="ProduttoreBean2" />
</util:list>
If you convert the decalaration of membri in Team class as below the code will work:
private List<Object> membri;
public List<Object> getMembri() {
return membri;
}
public void setMembri(List<Object> membri) {
this.membri = membri;
}
You should also provide "value-type" property for the list your are defining in your Test1xml.xml.
It should be like this:-
<property name="membri">
<util:list list-class="java.util.ArrayList" value-type="com.mkyong.core.Produttore">
<value>0</value>
<ref bean="ProduttoreBean2" />
</util:list>
</property>
First of all this is the first time that I am trying spring. I have a problem while connecting to a database using spring's JDBC template
Here's my code for AddEmployee Servlet:
package com.lftechnology.spring.jdbctemplate.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.lftechnology.spring.jdbctemplate.model.dao.EmployeeDAO;
import com.lftechnology.spring.jdbctemplate.model.dao.EmployeeDAOImpl;
import com.lftechnology.spring.jdbctemplate.model.dao.mysql.EmployeeMySql;
import com.lftechnology.spring.jdbctemplate.model.dto.Employee;
#WebServlet("/AddEmployee")
public class AddEmployee extends HttpServlet
{
private static final long serialVersionUID = 1L;
Employee employee;
public AddEmployee() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
RequestDispatcher dispatcher=request.getRequestDispatcher("addemployee.jsp");
dispatcher.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
EmployeeDAO employeeDAO= (EmployeeDAO) context.getBean("employeeDAO");
employee=new Employee();
String name=(String) request.getAttribute("name");
String designation=(String) request.getAttribute("designation");
employee.setName(name);
employee.setDesignation(designation);
employeeDAO.insert(employee);
RequestDispatcher dispatcher =request.getRequestDispatcher("success.jsp");
dispatcher.forward(request,response);
}
}
Corresponding class named EmployeeMySql for JDBC connection is
package com.lftechnology.spring.jdbctemplate.model.dao.mysql;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import com.lftechnology.spring.jdbctemplate.model.dao.EmployeeDAO;
import com.lftechnology.spring.jdbctemplate.model.dto.Employee;
public class EmployeeMySql extends JdbcTemplate implements EmployeeDAO
{
private DataSource dataSource;
public void setDataSource(DataSource dataSource)
{
System.out.println("Datasource here"+dataSource.toString());
try {
System.out.println("Datasource here"+dataSource.getLoginTimeout());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.dataSource = dataSource;
}
public void insert(Employee employee)
{
String query_sql;
query_sql="INSERT INTO EMPLOYEE (name,designation) VALUES (?,?,?)";
update(query_sql,new Object[]{employee.getName(),employee.getDesignation()});
}
#Override
public Employee retrieveAllData() {
// TODO Auto-generated method stub
return null;
}
}
Similarly my spring bean configuration is spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<bean id="dataSourcee"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/spring" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="employeeDAO" class="com.lftechnology.spring.jdbctemplate.model.dao.mysql.EmployeeMySql">
<property name="dataSource" ref="dataSourcee"/>
</bean>
<!-- import resource="Spring-Datasource.xml" />
<import resource="Spring-Customer.xml" /-->
</beans>
However i always end up with one error which i cant figure out at all.Error that i get is
HTTP Status 500 - Error creating bean with name 'employeeDAO' defined in class path resource [spring.xml]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'dataSource' is required
type Exception report
message Error creating bean with name 'employeeDAO' defined in class path resource [spring.xml]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'dataSource' is required
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeDAO' defined in class path resource [spring.xml]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'dataSource' is required
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1455)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:605)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:925)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:472)
org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
com.lftechnology.spring.jdbctemplate.controller.AddEmployee.doPost(AddEmployee.java:46)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
root cause
java.lang.IllegalArgumentException: Property 'dataSource' is required
org.springframework.jdbc.support.JdbcAccessor.afterPropertiesSet(JdbcAccessor.java:134)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:605)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:925)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:472)
org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
com.lftechnology.spring.jdbctemplate.controller.AddEmployee.doPost(AddEmployee.java:46)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
Could someone tell me what the error really is?
Help would be much appreciated.
In your setDataSource method, make a call to super.setDataSource. You have your own dataSource variable, however, the base class also does some initialization with the given dataSource instance and that is what is missed out.