Spring MVC Service class NullPointerException [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am trring to create an application where I am getting a problem. Here is the code
HomeController.java
#Controller
public class HomeController {
private EmployeeService employeeService;
#Autowired(required=true)
#Qualifier(value="employeeService")
public void setEmployeeService(EmployeeService employeeService)
{
this.employeeService = employeeService;
}
#RequestMapping("/index")
public ModelAndView indexWorld(#ModelAttribute("loginForm") Employee employee, ModelMap model) {
return new ModelAndView("index", "welcomeMessage","Hello Guest! welcome to our site");
}
#RequestMapping("/login")
public ModelAndView loginWorld(#ModelAttribute("loginForm") Employee employee, ModelMap model){
String result="", returnPage="";
if(this.employeeService.validateLogin(employee.getUsername(), employee.getPassword())){
result = "Welcome " + employee.getUsername();
returnPage = "home";
}
else{
result = "<BR>Login Failure";
returnPage = "index";
}
model.addAttribute("result", result);
return new ModelAndView(returnPage, model);
}
}
EmployeeServiceImpl.java
#Service
public class EmployeeServiceImpl implements EmployeeService {
/* (non-Javadoc)
* #see com.smart.service.EmployeeService#validateLogin(java.lang.String, java.lang.String)
*/
EmployeeDAO employeeDAO;
public void setEmployeeDAO(EmployeeDAO employeeDAO)
{
this.employeeDAO = employeeDAO;
}
#Override
public boolean validateLogin(String username, String password) {
// TODO Auto-generated method stub
return this.employeeDAO.validateLogin(username, password);
}
}
EmployeeDAOImpl.java
#Transactional(value="myTransactionManager")
public class EmployeeDaoImpl implements EmployeeDAO {
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory)
{
this.sessionFactory = sessionFactory;
}
#Override
public boolean validateLogin(String username, String password) {
return (long)this.sessionFactory.getCurrentSession().createQuery("SELECT COUNT(*) FROM EmployeeInfo WHERE username = :username AND password = :password")
.setString("username", username)
.setString("password", password).uniqueResult() > 0;
}
}
welcome-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:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
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/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"
xmlns:mvc="http://www.springframework.org/schema/mvc">
<context:annotation-config />
<context:component-scan base-package="com.smart" />
<mvc:annotation-driven />
<tx:annotation-driven transaction-manager="myTransactionManager" />
<bean id="employeeService" class="com.smart.service.EmployeeServiceImpl"></bean>
<bean id="employeeDAO" class="com.smart.dao.EmployeeDaoImpl"></bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/view/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="oracle.jdbc.OracleDriver"
p:url="jdbc:oracle:thin:#localhost:1521:IMS"
p:username="username"
p:password="password" />
<mvc:resources mapping="/resources/**" location="/resources/theme1/" />
</beans>
Error
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:979)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
root cause
java.lang.NullPointerException
com.smart.service.EmployeeServiceImpl.validateLogin(EmployeeServiceImpl.java:32)
com.smart.controller.HomeController.loginWorld(HomeController.java:38)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
I am getting in EmployeeServiceImpl.java on this line
return this.employeeDAO.validateLogin(username, password);
It seems I am getting null from validateLogin function although I am return value from validateLogin function. Why I am getting null?
EDIT
Now error
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'myTransactionManager' is defined: No matching PlatformTransactionManager bean found for qualifier 'myTransactionManager' - neither qualifier match nor bean name match!
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:979)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
root cause
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'myTransactionManager' is defined: No matching PlatformTransactionManager bean found for qualifier 'myTransactionManager' - neither qualifier match nor bean name match!
org.springframework.beans.factory.annotation.BeanFactoryAnnotationUtils.qualifiedBeanOfType(BeanFactoryAnnotationUtils.java:100)
org.springframework.beans.factory.annotation.BeanFactoryAnnotationUtils.qualifiedBeanOfType(BeanFactoryAnnotationUtils.java:56)
org.springframework.transaction.interceptor.TransactionAspectSupport.determineQualifiedTransactionManager(TransactionAspectSupport.java:377)
org.springframework.transaction.interceptor.TransactionAspectSupport.determineTransactionManager(TransactionAspectSupport.java:358)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:271)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
com.sun.proxy.$Proxy37.validateLogin(Unknown Source)
com.smart.service.EmployeeServiceImpl.validateLogin(EmployeeServiceImpl.java:33)
com.smart.controller.HomeController.loginWorld(HomeController.java:38)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)

It seems EmployeeDAO is not being injected in EmployeeServiceImpl, wire EmployeeDAO using #Autowire or #Inject, Second EmployeeDAOImpl has not been declared a component (not sure if you have declared already in xml) so declare it with #Repository and also #Autowire SessionFactory. Hope this will do..

From the stacktrace it appears your code never calls validateLogin on the dao. The dao is null because there's nothing telling Spring to wire your DAO into your service. Add an #Autowired annotation to the setter in the service for the dao, similar to what you have in the controller wiring the service into it.

Related

Cannot invoke "" because "" is null

i finally find it question tab.
why this error is 'boom'?????
i didn't understand spend two days.....
**java.lang.NullPointerException: Cannot invoke
"com.board.dao.BoardDao.listboard(com.board.dto.BoardDto)" because "this.bDao" is null**
at com.board.service.BoardService.listboard(BoardService.java:19)
at com.board.controller.BoardController.boardlist(BoardController.java:25)
at com.board.controller.BoardController.boardlist(BoardController.java:26)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.base/java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:213)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:626)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:543)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:616)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:818)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1626)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Unknown Source)
controller
#Controller
public class BoardController {
#Autowired
BoardService service;
#RequestMapping("/board")
public ModelAndView boardlist (ModelAndView mv ,BoardDto dto) {
System.out.println("boardlist ");
System.out.println(dto+"dto");
List<BoardDto> dtolist = service.listboard(dto);
mv.addObject("boardlist", dtolist);
mv.setViewName("boardlist");
return mv;
}
}
controller is fine.. i think..
service
#Service
public class BoardService {
#Autowired
BoardDao bDao;
public List<BoardDto> listboard(BoardDto dto) {
System.out.println("boardservice");
List<BoardDto> result = bDao.listboard(dto);
return result ;
}
}
this position is error why?? T.T
i think this method is error position but i don't know understand. why???
dao
public class BoardDao extends SqlSessionDaoSupport{
#Autowired
SqlSessionTemplate session;
public List<BoardDto> listboard(BoardDto dto) {
System.out.println("dao.");
List<BoardDto> result = session.selectList("boarddate.listboard", dto);
return result;
}
}
<?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 https://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">
<!-- Root Context: defines shared resources visible to all other web components -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:#localhost:1521:orcl"/>
<property name="username" value="board"/>
<property name="password" value="1234"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- classpath: -> src/main/resources -->
<property name="configLocation" value="classpath:myBatis/myBatis-config.xml"/>
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
<!-- DI -->
<bean class="com.board.service.BoardService"></bean>
<bean class="com.board.dao.BoardDao">
<property name="sqlSessionTemplate" ref="sqlSession"/>
</bean>
</beans>
root-context.xml
why error is 'boom'? i didn't understand.... T.T
--> edit more infomation to error
I think your problem is related with the lack of a #Component annotation in your BoardDao class.
The component should have a #Component annotation to instantiate the singleton to be injected in your Service Layer.
#Component
public class BoardDao extends SqlSessionDaoSupport{
#Autowired
SqlSessionTemplate session;
public List<BoardDto> listboard(BoardDto dto) {
System.out.println("dao.");
List<BoardDto> result = session.selectList("boarddate.listboard", dto);
return result;
}
}
If the problem persist, you may try with the #Repository annotation. Sadly I haven't used the class SqlSessionDaoSupport, so I don't know exactly the best annotation for that.
In my case it was with a Map, I wanted to increase its value, but this initial one will not exist, therefore it is null.
map.put(0, map.get(0) 1);
It was fixed by adding a validation, like so:
map.put(0, map.get(0) != null ? map.get(0) + 1 : 1);

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

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

Spring Framework integration test Java [duplicate]

This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
Closed 7 years ago.
I wrote an integration test on a Spring Framework controller and the and test runs correct. Application runs correct too. I have some exceptions that i want to fix. I can not fix the nullpoiner exception which come from LoginController at line 34. I saw that loginDelegate but how ti fix this ?
Controller class
#Controller
public class LoginController {
#Autowired
private LoginDelegate loginDelegate;
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView displayLogin(HttpServletRequest request, HttpServletResponse response, LoginBean loginBean) {
ModelAndView model = new ModelAndView("login");
model.addObject("loginBean", loginBean);
return model;
}
#RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView executeLogin(ModelAndView model, HttpServletRequest request, HttpServletResponse response,
#ModelAttribute("loginBean") LoginBean loginBean) {
try {
boolean isValidUser = loginDelegate.isValidUser(loginBean.getUsername(), loginBean.getPassword());
if (isValidUser) {
System.out.println("User Login Successful");
request.setAttribute("loggedInUser", loginBean.getUsername());
model = new ModelAndView("welcome");
} else {
model = new ModelAndView("login");
request.setAttribute("message", "Invalid credentials!!");
}
} catch (Exception e) {
e.printStackTrace();
}
return model;
}
}
Test Controller Class
#EnableWebMvc
#WebAppConfiguration
#Configuration
#ContextConfiguration(locations = { "classpath:/WEB-INF/spring-dispatcher-servlet.xml" })
public class LoginControllerTest {
#Autowired
protected WebApplicationContext wac;
private MockMvc mockMvc;
#Before
public void setup() throws Exception {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
this.mockMvc = standaloneSetup(new LoginController()).setViewResolvers(viewResolver).build();
}
#Test
public void testDisplayLogin() throws Exception {
this.mockMvc.perform(get("/login")).andExpect(status().isOk()).andExpect(view().name("login")).andDo(print())
.andExpect(forwardedUrl("/WEB-INF/views/login.jsp"));
}
#Test
public void testExecuteLogin() throws Exception {
this.mockMvc.perform(post("/login").param("username", "nikola").param("password", "pass")).andDo(print())
.andExpect(status().isOk()).andExpect(view().name("login"));
}
}
spring dispacher servlet
<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">
<context:component-scan base-package="com.nikola" />
<mvc:annotation-driven enable-matrix-variables="true" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="loginDelegate" class="com.nikola.integration.delegate.LoginDelegate">
<property name="userService" ref="userService"></property>
</bean>
<bean id="userService" class="com.nikola.integration.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
<bean name="userDao" class="com.nikola.integration.dao.impl.UserDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean name="loginController" class="com.nikola.integration.controller.LoginController">
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/store" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
</beans>
Exception
java.lang.NullPointerException
at com.nikola.integration.controller.LoginController.executeLogin(LoginController.java:34)
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:497)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:111)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:806)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:729)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:144)
at com.nikola.integration.controller.test.LoginControllerTest.testExecuteLogin(LoginControllerTest.java:51)
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:497)
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.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
In your test, you are instantiating a new LoginController :
this.mockMvc = standaloneSetup(new LoginController()).setViewResolvers(viewResolver).build();
This new instance is not managed by spring and the #Autowired field is not injected.
You should inject in your test the LoginController defined in your configuration, and initialize the mockMvc with this instance :
#Autowired
private LoginController controller;
...
this.mockMvc = standaloneSetup(c).setViewResolvers(viewResolver).build();

Spring Hibernate - NullPointerException SessionFactory

I got an error about SessionFactory.
CrudController.java
#Controller
public class CrudController {
#Autowired
private AlbumBo albumBo;
#RequestMapping(value = "/addAlbum")
#ResponseBody
public void addAlbum(
#RequestParam("NameRecordCompany") String nameRecordCompany,
#RequestParam("NameAlbum") String nameAlbum,
#RequestParam("YearName") String yearAlbum,
#RequestParam("NameArtist") String nameArtist,
#RequestParam("NameCategory") String nameCategory,
#RequestParam("SongList") String songList) throws JSONException {
Song temp = new Song();
ArrayList<Song> listaCanzoni = new ArrayList();
String songs = "{" + "\"songs\":" + songList + "}";
JSONObject jsonObjectSongList = new JSONObject(songs);
JSONArray jsonArraySongList = (JSONArray) jsonObjectSongList.get("songs");
for (int i = 0; i < jsonArraySongList.length(); i++) {
temp.setName((String) jsonArraySongList.getJSONObject(i).get("songName"));
temp.setDuration((String) jsonArraySongList.getJSONObject(i).get("songDuration"));
listaCanzoni.add(new Song(temp.getName(), temp.getDuration()));
}
Artist artist = new Artist(nameArtist);
Category category = new Category(nameCategory);
Album album = new Album(nameAlbum, yearAlbum);
album.setArtist(artist);
album.setCategory(category);
try {
albumBo.save(album); //line 67
JOptionPane.showMessageDialog(null, "albumDao.save(album) eseguita");
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
AlbumDaoImpl.java
public class AlbumDaoImpl implements AlbumDao {
#Autowired
SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory factory) {
this.sessionFactory = factory;
}
#Override
public void save(Album album) throws Exception {
Session session = sessionFactory.openSession(); //line 38
Transaction tx = null;
try {
tx = session.beginTransaction();
session.saveOrUpdate(album);
tx.commit();
} catch (HibernateException e) {
if (tx != null) {
tx.rollback();
} else {
e.printStackTrace();
}
} finally {
session.close();
}
}
}
AlbumBoImpl.java
public class AlbumBoImpl implements AlbumBo{
private AlbumDao albumDao;
static final Logger logger = Logger.getLogger(AlbumBoImpl.class);
public AlbumDao getAlbumDao() {
return albumDao;
}
public void setAlbumDao(AlbumDao albumDao) {
this.albumDao = albumDao;
}
#Override
public void save(Album album) throws Exception {
try{
albumDao.save(album); //line 35
}catch(Exception e){
logger.error(e);
throw e;
}
}
}
applicationContext.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:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"
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-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}"/>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>it.davidefruci.casadiscografica2.beans.Album</value>
<value>it.davidefruci.casadiscografica2.beans.Artist</value>
<value>it.davidefruci.casadiscografica2.beans.Song</value>
<value>it.davidefruci.casadiscografica2.beans.RecordCompany</value>
<value>it.davidefruci.casadiscografica2.beans.Category</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="dataSource" ref="dataSource" />
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- DAO -->
<bean id="albumDao" class="it.davidefruci.casadiscografica2.daoImpl.AlbumDaoImpl"/>
<bean id="artistDao" class="it.davidefruci.casadiscografica2.daoImpl.ArtistDaoImpl"/>
<bean id="categoryDao" class="it.davidefruci.casadiscografica2.daoImpl.CategoryDaoImpl"/>
<bean id="recordCompanyDao" class="it.davidefruci.casadiscografica2.daoImpl.RecordCompanyDaoImpl"/>
<bean id="songDao" class="it.davidefruci.casadiscografica2.daoImpl.SongDaoImpl"/>
<!-- BO -->
<bean id="albumBo" class="it.davidefruci.casadiscografica2.boImpl.AlbumBoImpl">
<property name="albumDao" ref="albumDao"></property>
</bean>
<bean id="artistBo" class="it.davidefruci.casadiscografica2.boImpl.ArtistBoImpl">
<property name="artistDao" ref="artistDao"></property>
</bean>
<bean id="categoryBo" class="it.davidefruci.casadiscografica2.boImpl.CategoryBoImpl">
<property name="categoryDao" ref="categoryDao"></property>
</bean>
<bean id="recordCompanyBo" class="it.davidefruci.casadiscografica2.boImpl.RecordCompanyBoImpl">
<property name="recordCompanyDao" ref="recordCompanyDao"></property>
</bean>
<bean id="songBo" class="it.davidefruci.casadiscografica2.boImpl.SongBoImpl">
<property name="songDao" ref="songDao"></property>
</bean>
I have a JSP where I add the datas that I want to save into my db.
When I click on the submit button, an Ajax call is invoked. This call invokes the CrudController, who should save data on my db with addAlbum method.
When the CrudController is invoked Tomcat tells me:
java.lang.NullPointerException
at it.davidefruci.casadiscografica2.daoImpl.AlbumDaoImpl.save(AlbumDaoImpl.java:38)
at it.davidefruci.casadiscografica2.boImpl.AlbumBoImpl.save(AlbumBoImpl.java:35)
at it.davidefruci.casadiscografica2.controllers.CrudController.addAlbum(CrudController.java:67)
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:497)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:777)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:706)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1521)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1478)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
I wrong something with the sessionFactory initialization?
<bean id="personDao"class="com.studytrails.tutorials.springhibernatesessionfactory.PersonDao">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
You will need to inject session factory in DAO you are using which will help you do CRUD operations on your Object either you can configure this in XML or using annotation.
Also please help your self by going through the given like below
Example of spring hibernate integration
Two things you can do, one is change to inject the SessionFactory to Dao by yourself.
<!-- DAO -->
<bean id="albumDao" class="it.davidefruci.casadiscografica2.daoImpl.AlbumDaoImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
You can do this for all DAOs.
Or
put a component scan on the applicationContext.xml XML configuration so that the SessionFactory will get Autowired.
<context:component-scan base-package="it.davidefruci.casadiscografica2"/>

Concurrent testing with TestNG and Spring Transaction

I have a service class, the service class is annotated with #Transactional(propagation = Propagation.REQUIRES_NEW) and its public method is defined in an interface:
public interface UniqueKeyGeneratorService {
void initializeUniqueKeys(Entity entity);
}
#Transactional(propagation = Propagation.REQUIRES_NEW)
public final class KeyGeneratorServiceImpl implements UniqueKeyGeneratorService, DisposableBean {
private final UniqueKeyGeneratorStrategy strategy;
private KeyGeneratorServiceImpl(final UniqueKeyGeneratorStrategy strategy) {
this.strategy = strategy;
}
#Override
public void initializeUniqueKeys(final Entity entity) {
// ... the business logic
}
// ... some private methods
#Override
public void destroy() {
strategy.destroy();
}
}
And the bean is created using a FactoryBean (to initialize the strategy).
I want to test the service, so I configured an embedded H2 database, defined a connection pool using Apache Commons DBCP and write proper test code as:
#ContextConfiguration("/path/to/xml/config/file.xml")
#Transactional
public class TestUniqueKeyGeneratorService extends AbstractTransactionalTestNGSpringContextTests {
#Autowired
private UniqueKeyGeneratorService service;
#Test
#Rollback(false)
public void testCodeGeneration() {
final Department department1 = new Department();
department1.setName("Abcd");
service.initializeUniqueKeys(department1);
final String code = department1.getCode();
Assert.assertNotNull(code);
}
// ... some more test methods
}
and have
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.h2.Driver"/>
<property name="url" value="jdbc:h2:mem:db1"/>
<property name="username" value="sa"/>
<property name="password" value=""/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven/>
<bean id="uniqueKeyGeneratorService"
class="com.mycompany.uniquekey.UniqueKeyGeneratorServiceFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
the test passes, but when I change the #Test annotation to #Test(invocationCount = 10, singleThreaded = false, threadPoolSize = 2) following exception occures:
org.springframework.transaction.CannotCreateTransactionException: Could not open JDBC Connection for transaction; nested exception is java.sql.SQLException: Connection is closed.
at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:240) ~[org.springframework.jdbc-3.1.3.RELEASE.jar:3.1.3.RELEASE]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:371) ~[org.springframework.transaction-3.1.3.RELEASE.jar:3.1.3.RELEASE]
at org.springframework.test.context.transaction.TransactionalTestExecutionListener$TransactionContext.startTransaction(TransactionalTestExecutionListener.java:514) ~[org.springframework.test-3.1.3.RELEASE.jar:3.1.3.RELEASE]
at org.springframework.test.context.transaction.TransactionalTestExecutionListener.startNewTransaction(TransactionalTestExecutionListener.java:272) ~[org.springframework.test-3.1.3.RELEASE.jar:3.1.3.RELEASE]
at org.springframework.test.context.transaction.TransactionalTestExecutionListener.beforeTestMethod(TransactionalTestExecutionListener.java:165) ~[org.springframework.test-3.1.3.RELEASE.jar:3.1.3.RELEASE]
at org.springframework.test.context.TestContextManager.beforeTestMethod(TestContextManager.java:358) ~[org.springframework.test-3.1.3.RELEASE.jar:3.1.3.RELEASE]
at org.springframework.test.context.testng.AbstractTestNGSpringContextTests.springTestContextBeforeTestMethod(AbstractTestNGSpringContextTests.java:146) [org.springframework.test-3.1.3.RELEASE.jar:3.1.3.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.6.0_31]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) ~[na:1.6.0_31]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) ~[na:1.6.0_31]
at java.lang.reflect.Method.invoke(Method.java:597) ~[na:1.6.0_31]
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:80) [org.testng-6.8.jar:6.8-201210030754]
at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:564) [org.testng-6.8.jar:6.8-201210030754]
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:213) [org.testng-6.8.jar:6.8-201210030754]
at org.testng.internal.Invoker.invokeMethod(Invoker.java:653) [org.testng-6.8.jar:6.8-201210030754]
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901) [org.testng-6.8.jar:6.8-201210030754]
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231) [org.testng-6.8.jar:6.8-201210030754]
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127) [org.testng-6.8.jar:6.8-201210030754]
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111) [org.testng-6.8.jar:6.8-201210030754]
at org.testng.internal.thread.ThreadUtil$2.call(ThreadUtil.java:64) [org.testng-6.8.jar:6.8-201210030754]
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303) [na:1.6.0_31]
at java.util.concurrent.FutureTask.run(FutureTask.java:138) [na:1.6.0_31]
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) [na:1.6.0_31]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) [na:1.6.0_31]
at java.lang.Thread.run(Thread.java:662) [na:1.6.0_31]
Caused by: java.sql.SQLException: Connection is closed.
at org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.checkOpen(PoolingDataSource.java:185) ~[org.apache.commons-dbcp-1.4.jar:1.4]
at org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.getAutoCommit(PoolingDataSource.java:234) ~[org.apache.commons-dbcp-1.4.jar:1.4]
at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:218) ~[org.springframework.jdbc-3.1.3.RELEASE.jar:3.1.3.RELEASE]
... 24 common frames omitted
any idea how to handle this exception?
p.s. I reviewed H2 documentations, and it supports multiple connections in embedded mode.
The answer is located in TestNG multithreaded test with Spring #Transactional

Categories