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.
Related
I wrote the below code inorder to implement Spring Exception handling. When I run the code it needs to throw an error at the below line and the corresponding exception handler should execute. But, it is not executing. May I know what is wrong in my code. Thanks in advance
throw new SpringException("Error", retStatus);
Code:
#Controller
public class RestController {
#ExceptionHandler(SpringException.class)
public String handleCustomException(SpringException ex) {
String jsonInString = "{}";
JSONObject json = new JSONObject();
Map<String,String> errorMap = new HashMap<String,String>();
errorMap.put("errorMessage",ex.getMessage());
System.out.println("Inside exception handler");
json.putAll(errorMap);
jsonInString = json.toJSONString();
logger.info(jsonInString);
return jsonInString;
}
#RequestMapping(value = "/v1/dist_list/{emailId}/members", method = RequestMethod.GET)
public #ResponseBody String getDistributionListMember(#PathVariable String emailId) throws Exception, SpringException {
String retStatus = null;
retStatus = dataServices.getDistributionListMember(emailId, callerId);
if (!retStatus.isEmpty()) {
if (retStatus.contains("callerid is not valid")) {
throw new SpringException("Error", retStatus);
}
}
}
SpringException class
package com.uniteid.model;
import org.springframework.http.HttpStatus;
public class SpringException extends RuntimeException {
private static final long serialVersionUID = 1L;
private String errCode;
private String errMsg;
public String getErrCode() {
return errCode;
}
public void setErrCode(String errCode) {
this.errCode = errCode;
}
public String getErrMsg() {
return errMsg;
}
public void setErrMsg(String errMsg) {
this.errMsg = errMsg;
}
public SpringException(String errCode, String errMsg) {
this.errCode = errCode;
this.errMsg = errMsg;
}
}
Below is my Spring-config.xml file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.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-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:component-scan base-package="com.uniteid.controller" />
<mvc:annotation-driven
content-negotiation-manager="contentNegociationManager" />
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:uniteidrest.properties" />
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url">
<value>${eidms.url}</value>
</property>
<property name="username">
<value>${eidms.username}</value>
</property>
<property name="password">
<value>${eidms.password}</value>
</property>
</bean>
<!-- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"
/> <property name="url" value="jdbc:oracle:thin:#un.org:1521:EIDMSUAT"
/> <property name="username" value="EIDMSUAT" /> <property name="password"
value="NewPass" /> </bean> -->
<bean id="contentNegociationManager"
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="defaultContentType" value="application/json" />
<property name="ignoreAcceptHeader" value="true" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.uniteid.model.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.connection.pool_size">10</prop>
</props>
</property>
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean class = "org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name = "exceptionMappings">
<props>
<prop key = "com.uniteid.model.SpringException">
ExceptionPage
</prop>
</props>
</property>
<property name = "defaultErrorView" value = "error"/>
</bean>
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean id="dataDao" class="com.uniteid.dao.DataDaoImpl"></bean>
<bean id="dataServices" class="com.uniteid.services.DataServicesImpl"></bean>
</beans>
I get the below error in the console at this line of the code
throw new SpringException("Error", retStatus);
2017-06-01 12:52:58 DEBUG DispatcherServlet:1175 - Handler execution resulted in exception - forwarding to resolved error view: ModelAndView: reference to view with name '{"errorMessage":null}'; model is {}
com.uniteid.model.SpringException
at com.uniteid.controller.RestController.getDistributionListMember(RestController.java:)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
I have a method that should run at some delay, make request to api and add the new photo to database. So, addPhoto is working fine. It can print some info, make a request, but doesn't add the photo. I checked the database and there are only one photo, that i added manually.
#Component("restBean")
#Service
public class RestService {
private static final String url1 = "https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?sol=1324&camera=fhaz&api_key=DEMO_KEY";
private PhotoDao photoDao;
#Autowired
public void setPhotoDao(PhotoDao photoDao) {
this.photoDao = photoDao;
}
#Scheduled(fixedRate = 5000)
public void addPhoto() {
System.out.println("TIME HAS COME");
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Response> response = restTemplate
.getForEntity(url1,
Response.class);
Photo[] photos = response.getBody().getPhotos();
this.photoDao.save(photos[0]);
}
}
I have tested this method and all works except the last string. I checked that i get the response and can get the object from it.
this.photoDao.save(photos[0]);
That's my DAO class
#Repository
public class PhotoDaoImpl implements PhotoDao {
private static final Logger logger = LoggerFactory.getLogger(PhotoDaoImpl.class);
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Override
public void save(Photo photo) {
Session session = this.sessionFactory.getCurrentSession();
session.persist(photo);
logger.info("Photo successfully saved. Photo details: {}", photo);
}
#Override
public Photo findOne(int id) {
Session session = this.sessionFactory.getCurrentSession();
Photo photo = (Photo) session.load(Photo.class, new Integer(id));
logger.info("Photo successfully loaded. Photo details: {}", photo);
return photo;
}
#Override
#SuppressWarnings("unchecked")
public List<Photo> getAll() {
Session session = this.sessionFactory.getCurrentSession();
That's my spring xml configuration
<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:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">
<!-- This helps in mapping the logical view names to directly view files under a certain pre-configured directory -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- Database Information -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3306/DayDatabase"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!-- Hibernate 4 SessionFactory Bean definition -->
<bean id="hibernate4AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan">
<list>
<value>net.yan.model</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- It register the beans in context and scan the annotations inside beans and activate them -->
<context:component-scan base-package="net.yan"/>
<!-- This allow for dispatching requests to Controllers -->
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
<!-- PhotoDao and PhotoService beans -->
<bean id="photoDao" class="net.yan.dao.PhotoDaoImpl">
<property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory"/>
</bean>
<bean id="photoService" class="net.yan.service.PhotoServiceImpl">
<property name="photoDao" ref="photoDao"/>
</bean>
<bean id="restService" class="net.yan.service.RestService">
<property name="photoDao" ref="photoDao"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory"/>
</bean>
<task:scheduled-tasks scheduler="myScheduler">
<task:scheduled ref="restBean" method="addPhoto" fixed-delay="5000"/>
</task:scheduled-tasks>
<task:scheduler id="myScheduler"/>
UPD: To be clear, i have another method, that make request and add to database. It's in the same class that doesn't work.
#EventListener(ContextRefreshedEvent.class)
#Transactional
public void contextRefreshedEvent() {
if (this.photoDao.checkDataBase()) {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Response> response = restTemplate
.getForEntity(url,
Response.class);
Photo[] photos = response.getBody().getPhotos();
this.photoDao.save(photos[0]);
}
}
UPD2: There's link to full project https://github.com/Kabowyad/Test-Project/tree/api-test/src/main/java/net/yan/service
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.
I am trying to define the transaction in my spring mvc project but having problem:
// xml file
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns=
"http://www.springframework.org/schema/beans"
xmlns:xsi=
"http://www.w3.org/2001/XMLSchema-instance"
xmlns:context
="http://www.springframework.org/schema/context"
xmlns:p=
"http://www.springframework.org/schema/p"
xmlns:tx=
"http://www.springframework.org/schema/tx"
xsi:schemaLocation=
"http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- Enable Annotation based Declarative Transaction Management -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- Creating TransactionManager Bean, since JDBC we are creating of type DataSourceTransactionManager -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- Initialization for data source -->
<bean id="dataSource" class= "org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost/bhaiyag_devgrocery"></property>
<property name="username" value="newuser"></property>
<property name="password" value="kim"></property>
</bean>
<bean id="CategoriesDaoImpl" class="org.kmsg.dao.daoImpl.CategoriesDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="CityDaoImpl" class="org.kmsg.dao.daoImpl.CityDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="CustomerDaoImpl" class="org.kmsg.dao.daoImpl.CustomerDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
// This is class where i want to apply the transaction
public class CustomerOrderAdapter
{
public void displayCustomerOrder(String mobileNo)
{ }
#Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, readOnly = true)
public Map<String, Object> createCustomerOrderData(SalesCommandObject salesCommandObject,long OrderForDelete) throws Exception
{
Map <String, Object> data = new HashMap<String, Object>();
try
{
salesDaoImpl.deleteSalesitems(OrderNo);
salesDaoImpl.deleteSales(OrderNo);
salesDaoImpl.insertSalesItems(updatedOn,OrderNo,CustmobileNo);
salesDaoImpl.insertSales(totalSale, SlotNo, OrderNo);
}
catch(IndexOutOfBoundsException ex)
{
System.out.println("No Record to Save");
data.put("status", "No Record to Save");
}
catch(Exception e)
{
System.out.println(e.toString());
data.put("status", e);
}
data.put("status", "Purchase Successfull");
return data;
}
}
// Help me and suggest , How to implement transaction;
I am trying to save data to database with Spring's JdbcTemplate, but I get this error message. If I do it normal way with PreparedStatements it's working.
My CarDAO class:
#Repository
#Service
public class CarDAO implements CarDAOService {
private JdbcTemplate jdbcTemplate;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void saveCarToDB(CarBean carbean) {
final String sql = "insert into car (make, model) values (?,?)";
Object[] parameters = new Object[] {carbean.getMake()+
carbean.getModel()};
//if I do here system.out.print(Arrays.toString(parameters));
//it will print right make/model.
jdbcTemplate.update(sql, parameters);
//console says it is that row above, but I don't get how. Both parameters has values?
//WARNING: StandardWrapperValve[spring-dispatcher]: Servlet.service() for servlet
//springdispatcher threw exception
}
Spring-base.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">
<context:component-scan base-package="bean, dao" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/Jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- DATA SOURCE -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="org.mariadb.jdbc.Driver" />
<property name="url" value="jdbc:mariadb://XXXXX" />
<property name="username" value="XXXXX" />
<property name="password" value="XXXXX" />
<property name="initialSize" value="1" />
<property name="maxActive" value="5" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<mvc:annotation-driven />
</beans>
I didn't include my Controller or CarDAOService class, because I think the problem isn't there. They are forwarding right parameters to CarDAO class.
You need to put the #Autowired annotation on your setter:
#Autowired
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
Autowired bean via #Autowired, and it can be applied on setter method, constructor or a field.
Try this
#Autowired
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}