Spring3 - Autowired is not happening. The object is null - java

servlet.xml
I am using annotation instead of creating bean in XML.
And I have added the "context: annotation-config" in my XML
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" 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.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.hemanths.expense.manager"/>
<mvc:annotation-driven/>
<tx:annotation-driven/>
<context:annotation-config />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="configLocation" value="WEB-INF/hibernate.cfg.xml"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
</beans>
UserDaoImpl.java
package com.hemanths.expense.manager.hibernate.dao.impl;
import com.hemanths.expense.manager.hibernate.dao.UserDao;
import com.hemanths.expense.manager.hibernate.entity.User;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository
public class UserDaoImpl implements UserDao {
#Autowired
private SessionFactory sessionFactory;
public UserDaoImpl() {
}
public UserDaoImpl(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Override
public void addUser(User user) {
sessionFactory.getCurrentSession().save(user);
}
}
UserService.java
package com.hemanths.expense.manager.service.impl;
import com.hemanths.expense.manager.hibernate.dao.UserDao;
import com.hemanths.expense.manager.hibernate.entity.User;
import com.hemanths.expense.manager.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
#Service
public class UserServiceImpl implements UserService {
#Autowired
private UserDao userDao;
public UserServiceImpl() {
}
public UserServiceImpl(UserDao userDao){
this.userDao = userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
#Override
#Transactional
public void addUser(User user) {
userDao.addUser(user);
}
UserServiceImplTest.java
public class UserServiceImplTest {
#Autowired
UserService userService;
#Test
public void shouldAddUser() {
User user = new User("firstName", "lastName", new Date(), "M", "username", "password");
userService.addUser(user);
}
}
Stacktrace
java.lang.NullPointerException
at com.hemanths.expense.manager.service.impl.UserServiceImplTest.shouldAddUser(UserServiceImplTest.java:18)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:74)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:211)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:67)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Directory Structure

I got an answer. Thanks #Andrei Stefan.
Because i am running a test, I have to annotate test like the below with your xml file path.
#ContextConfiguration(locations = {"classpath:mvc-dispatcher-servlet.xml"})
#RunWith(SpringJUnit4ClassRunner.class)
public class UserServiceImplTest {
#Autowired
UserService userService;
#Test
public void shouldAddUser() {
User user = new User("firstName", "lastName", new Date(), "M", "username", "password");
userService.addUser(user);
}
}

Example usage for your hibernate;
<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:mvc="http://www.springframework.org/schema/mvc" 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.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.base.package"/>
<mvc:annotation-driven/>
<tx:annotation-driven/>
<context:annotation-config />
<bean id="_hibernateSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="configLocation" value="WEB-INF/hibernate.cfg.xml"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- userDao Repo -->
<bean id="_userDao"
class="com.hemanths.expense.manager.hibernate.dao.impl.UserDaoImpl">
<property name="_hibernateSessionFactory">
<ref bean="_hibernateSessionFactory"></ref>
</property>
</bean>
<!-- userService Repo -->
<bean id="_userDao"
class="com.hemanths.expense.manager.service.impl.UserServiceImpl">
<property name="_hibernateSessionFactory">
<ref bean="_hibernateSessionFactory"></ref>
</property>
</bean>
</beans>
Add hibernate class in your DaoImpl with getter and setter :
private SessionFactory _hibernateSessionFactory;
use autowire in your controller where you want :
#Autowired
private UserServiceImpl _userServiceImpl;

As has been mentioned in the comments, you do not need to create beans for your service and DAO classes in your servlet.xml file:
<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:mvc="http://www.springframework.org/schema/mvc" 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.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.hemanths.expense.manager"/>
<mvc:annotation-driven/>
<tx:annotation-driven/>
<context:annotation-config />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="configLocation" value="WEB-INF/hibernate.cfg.xml"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
</beans>
You also do not need to supply constructors for your service and DAO classes, because they are Spring components:
#Repository("userDao")
public class UserDaoImpl implements UserDao {
#Autowired
private SessionFactory sessionFactory;
// Methods here
}
#Service
public class UserServiceImpl implements UserService {
#Autowired
private UserDao userDao;
// Methods here
}

Related

Exception:No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

I am getting error after deploying the application. I have checked similar questions but still could not resolve the error. I have used #Transactional for the service class as well as
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:656)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63)
org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:687)
com.utd.dao.CustomerDaoImpl.getAllCustomer(CustomerDaoImpl.java:22)
com.utd.service.CustomerManagerImpl.getAllCustomer(CustomerManagerImpl.java:23)
com.utd.controller.CustomerController.listCustomers(CustomerController.java:22)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
I have following project files:
The controller:
#Controller
public class CustomerController {
#Autowired
private CustomerManager customerManager;
#RequestMapping(value="/", method= RequestMethod.GET)
public String listCustomers(ModelMap map){
map.addAttribute("customer", new Customer());
map.addAttribute("customerList", customerManager.getAllCustomer());
return "CustomerList";
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String addCustomer(#ModelAttribute(value="customer") Customer customer, BindingResult result)
{
customerManager.addCustomer(customer);
return "redirect:/";
}
#RequestMapping("/delete/{customerId}")
public String deleteEmplyee(#PathVariable("customerId") Integer customerId)
{
customerManager.deleteCustomer(customerId);
return "redirect:/";
}
public void setCustomerManager(CustomerManager customerManager) {
this.customerManager = customerManager;
}
}
The dao class
public class CustomerDaoImpl implements CustomerDao{
#Autowired
private SessionFactory sessionFactory;
public void addCustomer(Customer customer) {
this.sessionFactory.getCurrentSession().save(customer);
}
#SuppressWarnings("unchecked")
public List<Customer> getAllCustomer() {
return this.sessionFactory.getCurrentSession().createQuery("from Customer").list();
}
public void deleteCustomer(Integer customerId) {
Customer customer = (Customer) sessionFactory.getCurrentSession().load(Customer.class, customerId);
if (null != customer) {
this.sessionFactory.getCurrentSession().delete(customer);
}
}
}
The Dto:
#Entity
#Table(name="Customer")
public class Customer {
#Id
#Column(name="ID")
#GeneratedValue
private int id;
#Column(name="NAME")
private String name;
#Column(name="CONTACT")
private String contact;
#Column(name="EMAIL")
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
customer-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/util/ http://www.springframework.org/schema/util/spring-util.xsd">
<context:annotation-config />
<context:component-scan base-package="com.utd.controller" />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/view/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages"></property>
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties"></bean>
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
p:password="${jdbc.password}"></bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</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="customerDao" class="com.utd.dao.CustomerDaoImpl"></bean>
<bean id="customerManager" class="com.utd.service.CustomerManagerImpl"></bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
</beans>
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
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">
<mvc:annotation-driven />
<context:component-scan base-package="com.utd" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
Manager class Implementation
package com.utd.service;
import com.utd.dao.CustomerDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.utd.dto.Customer;
import javax.transaction.Transactional;
import java.util.List;
#Service
public class CustomerManagerImpl implements CustomerManager {
#Autowired
private CustomerDao customerDao;
#Transactional
public void addCustomer(Customer customer) {
customerDao.addCustomer(customer);
}
#Transactional
public List<Customer> getAllCustomer() {
return customerDao.getAllCustomer();
}
#Transactional
public void deleteCustomer(Integer customerId) {
customerDao.deleteCustomer(customerId);
}
public void setCustomerDao(CustomerDao customerDao) {
this.customerDao = customerDao;
}
}
I would like to know how to resolve the error.

How to manage persistence using Spring and Hibernate

I just started a web application in Spring using Hibernate and this is the way I figured(after finding few ways of doing it):
GenericDAO
public interface GenericDAO<T extends DomainModel> {
public T getById(Integer id);
public List<T> getAll();
public void saveEntity(T object);
public void deleteEntity(T object);
}
GenericDAOImpl
public class GenericDAOImpl<T extends DomainModel> implements GenericDAO<T> {
private Class<T> type;
#Autowired
protected SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory){
this.sessionFactory = sessionFactory;
}
public Session getCurrentSession(){
return sessionFactory.getCurrentSession();
}
public GenericDAOImpl(Class<T> type) {
super();
this.type = type;
}
#SuppressWarnings("unchecked")
#Transactional(readOnly = true)
#Override
public T getById(Integer id) {
if( id == null){
return null;
} else {
return (T) getCurrentSession().get(type, id);
}
}
#SuppressWarnings("unchecked")
#Transactional(readOnly = true)
#Override
public List<T> getAll() {
return getCurrentSession().createQuery("select o from " + type.getName() + " o").list();
}
#Transactional(readOnly = true)
#Override
public void saveEntity(T object) {
getCurrentSession().persist(object);
}
#Transactional(readOnly = true)
#Override
public void deleteEntity(T object) {
getCurrentSession().delete(object);
}
}
UserService
public interface UserService {
public void addUser(User user);
public List<User> getUsers();
public User get(Integer id);
public void delete(User user);
}
UserServiceImpl
#Service
#Transactional
public class UserServiceImpl implements UserService {
#Autowired
private GenericDAO<User> userDAO;
#Override
public void addUser(User user) {
userDAO.saveEntity(user);
}
#Override
public User get(Integer id) {
return userDAO.getById(id);
}
#Override
public void delete(User user) {
userDAO.deleteEntity(user);
}
#Override
public List<User> getUsers() {
return userDAO.getAll();
}
}
UserController
#Controller
public class UserController {
#Autowired
private UserService userService;
#RequestMapping(value = "test", method = RequestMethod.GET)
public String test(){
User u1 = userService.get(1);
return "test";
}
}
Configuration hibernate
<?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:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.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="myDataSource" 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/online_auction" />
<property name="username" value="root" />
<property name="password" value="123456" />
</bean>
<!-- Hibernate 4 SessionFactory Bean definition -->
<bean id="mySessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="online_auction.domain_model" />
<property name="hibernateProperties">
<props>
<!-- SQL dialect depends on which database you connect to -->
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="mySessionFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<mvc:annotation-driven/>
</beans>
Configuration Spring
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
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/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
<import resource="classpath:dataSource.xml"/>
<mvc:annotation-driven />
<context:component-scan base-package="online_auction"/>
<mvc:resources location="css" mapping="/css/**" />
<mvc:resources location="images" mapping="/images/**" />
<!-- Tiles configuration -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles2.TilesView
</value>
</property>
</bean>
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
</beans>
My questions are:
How is the management of the database connection made ? Session per
web Request ? When is the database connection opened and closed ?
Should I create the session in the Service and pass it as parameter to the repositories constructors. Should I also manipulate the session methods like : open session, begin transaction, commit, close session.
Since is my first layered application using Repository and Service any suggestions on how to manage database connection/session/transaction are more then welcomed. Thanks in advance!
A pointer for few of your queries - Consider using Spring's OpenSessionInViewInterceptor, it binds Hibernate Session to the thread for the entire processing of the request. You can have it's bean defined as:
<bean name="openSessionInViewInterceptor"
class="org.springframework.orm.hibernate4.support.OpenSessionInViewInterceptor">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
and referred in "interceptors" property of SimpleUrlHandlerMapping bean in Spring's context.xml.
More detail on OpenSessionInViewInterceptor here.

Hibernate & Spring: EntityManager is Null

I'm setting up a Project with Spring and Hibernate. I created an abstract DAO class that contains an EntityManager. When I want to use this EntityManager, it's null and I dont understand why. Maybe you can help me.
My persistence-context
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
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.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<import resource="persistence-beans.xml" />
<mvc:annotation-driven />
<bean id="jdbcPropertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="classpath:META-INF/mysql.properties" />
<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="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="persistenceUnit" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="${hibernate.show_sql}" />
<property name="generateDdl" value="${hibernate.generate_ddl}" />
<property name="databasePlatform" value="${hibernate.dialect}" />
</bean>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="personDao" class="com.patrickzinner.dao.PersonDao" />
<tx:annotation-driven transaction-manager="transactionManager" />
PersonDao.java:
#Repository
#Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class PersonDao extends AbstractDao<Person> {
public PersonDao() {
super(Person.class);
}
}
AbstractDao.java
#SuppressWarnings("unchecked")
#Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public abstract class AbstractDao<T> {
#PersistenceContext
protected EntityManager em;
private Class<T> entityClass;
public AbstractDao(Class<T> entityClass) {
this.entityClass = entityClass;
}
public AbstractDao() {
}
public void create(T entity) {
this.em.persist(entity);
}
public void edit(T entity) {
this.em.merge(entity);
}
public void remove(T entity) {
this.em.remove(this.em.merge(entity));
}
public T find(long primaryKey) {
return this.em.find(entityClass, primaryKey);
}
#SuppressWarnings("rawtypes")
public List<T> findAll() {
CriteriaQuery cq = this.em.getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return this.em.createQuery(cq).getResultList();
}
}
Thanks in advance!
An entity manager can only be injected in transaction classes. In other words, it can only be injected in a EJB. Other classe must use an EntityManagerFactory to create and destroy an EntityManager.
but your AbstractDAO is not EJB you can not use EntityManager directly.
solution
#PersistenceUnit(unitName = "test")
private EntityManagerFactory entityManagerFactory;
EntityManager entityManager = entityManagerFactory.createEntityManager();
then perform operation using emtityManager.
alternatively you can use container managed Transaction using JNDI lookup..
let me know for any issues.
Try adding <context:annotation-config /> to your persistence-context. This section of the reference manual may help you to use #PersistenceContext.

Spring Framework - Hibernate

I am going to be confused. I am trying to get Hibernate work with Spring, I can not get rid of a BeanCreationException. Please help me. I am new to Spring (and also Hibernate).
The problem is caused in a controller, having a private attribute userService which is annotated with #Autowired.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.aerts.service.UserService com.aerts.controller.TestController.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.aerts.service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
I am really confused, please help me somebody.
Here is my root-context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<tx:annotation-driven />
<context:component-scan base-package="com.aerts.controller">
</context:component-scan>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="classpath:application.properties" />
<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://....."/>
<property name="username" value="....."/>
<property name="password" value="....."/>
<property name="initialSize" value="5"/>
<property name="maxActive" value="20"/>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<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">create</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Here is my User.java
package com.aerts.domain;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="User")
public class User {
#Id
#GeneratedValue()
#Column(name="id")
int id;
#Column(name="gender")
private Gender gender;
#Column(name="birthdate")
private Date birthdate;
#Column(name="firstname")
private String firstname;
#Column(name="surname")
private String surname;
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public Date getBirthdate() {
return birthdate;
}
public void setBirthdate(Date age) {
this.birthdate = age;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname.trim();
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname.trim();
}
}
My UserDaoImpl:
package com.aerts.dao;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import com.aerts.domain.User;
#Service
public class UserDaoImpl implements UserDao{
#Autowired
private SessionFactory sessionFactory;
#Override
public void addUser(User user) {
sessionFactory.getCurrentSession().save(user);
}
#Override
public List<User> listUser() {
return sessionFactory.getCurrentSession().createQuery("from User")
.list();
}
#Override
public void removeUser(int id) {
User user = (User) sessionFactory.getCurrentSession().get(
User.class, id);
if (user != null) {
sessionFactory.getCurrentSession().delete(user);
}
}
#Override
public void updateUser(User user) {
sessionFactory.getCurrentSession().update(user);
}
}
And my UserServiceImpl:
package com.aerts.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.aerts.dao.UserDao;
import com.aerts.domain.User;
#Service
public class UserServiceImpl implements UserService {
#Autowired
private UserDao userDao;
#Override
#Transactional
public void addUser(User user) {
userDao.addUser(user);
}
#Override
#Transactional
public List<User> listUser() {
return userDao.listUser();
}
#Override
#Transactional
public void removeUser(int id) {
userDao.removeUser(id);
}
#Override
#Transactional
public void updateUser(User user) {
userDao.updateUser(user);
}
}
I would really appreciate it if somebody could help me, i am going to be desperate...
Add the service class package to the component-scan base-package list in the application context file
<context:component-scan
base-package="
com.aerts.controller
com.aerts.service">
</context:component-scan>
I'm not expertise in spring but I assume that you have a problem with your service, if you use an interface you should inject ut and not your class...
see this track...
Spring expected at least 1 bean which qualifies as autowire candidate for this dependency

Java+Spring: SEVERE Servletservice

I dont know what is wrong in my listContacts in controller
map.put("contactList", contactService.listContact());
Can somebody help me?
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/test] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at pl.ivmx.contact.controller.ContactController.listContacts(ContactController.java:26)
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:601)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
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:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1001)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
package pl.ivmx.contact.controller;
import java.util.Map;
import pl.ivmx.contact.dao.ContactDAO;
import pl.ivmx.contact.form.Contact;
import pl.ivmx.contact.service.ContactService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class ContactController {
#Autowired
private ContactService contactService;
#RequestMapping("/contact")
public String listContacts(Map<String, Object> map) {
map.put("contact", new Contact());
map.put("contactList", contactService.listContact());
return "/contact";
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String addContact(#ModelAttribute("contact") Contact contact,
BindingResult result) {
contactService.addContact(contact);
return "redirect:/contact";
}
#RequestMapping("/delete/{contactId}")
public String deleteContact(#PathVariable("contactId") Integer contactId) {
contactService.removeContact(contactId);
return "redirect:/contact";
}
}
package pl.ivmx.contact.dao;
import java.util.List;
import pl.ivmx.contact.form.Contact;
public interface ContactDAO {
public void addContact(Contact contact);
public List<Contact> listContact();
public void removeContact(Integer id);
}
package pl.ivmx.contact.dao;
import java.util.List;
import pl.ivmx.contact.form.Contact;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
#Repository
public class ContactDAOImpl implements ContactDAO {
#Autowired
private SessionFactory sessionFactory;
public void addContact(Contact contact) {
sessionFactory.getCurrentSession().save(contact);
}
public List<Contact> listContact() {
return sessionFactory.getCurrentSession().createQuery("from Contact").list();
}
public void removeContact(Integer id) {
Contact contact = (Contact) sessionFactory.getCurrentSession().load(
Contact.class, id);
if (null != contact) {
sessionFactory.getCurrentSession().delete(contact);
}
}
}
package pl.ivmx.contact.service;
import java.util.List;
import pl.ivmx.contact.form.Contact;
public interface ContactService {
public void addContact(Contact contact);
public List<Contact> listContact();
public void removeContact(Integer id);
}
package pl.ivmx.contact.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pl.ivmx.contact.dao.ContactDAO;
import pl.ivmx.contact.form.Contact;
#Service
public class ContactServiceImpl implements ContactService {
#Autowired
private ContactDAO contactDAO;
#Transactional
public void addContact(Contact contact) {
contactDAO.addContact(contact);
}
#Transactional
public List<Contact> listContact() {
return contactDAO.listContact();
}
#Transactional
public void removeContact(Integer id) {
contactDAO.removeContact(id);
}
}
package pl.ivmx.contact.form;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="CONTACTS")
public class Contact {
#Id
#Column(name="ID")
#GeneratedValue
private Integer id;
#Column(name="FIRSTNAME")
private String firstname;
#Column(name="LASTNAME")
private String lastname;
#Column(name="EMAIL")
private String email;
#Column(name="TELEPHONE")
private String telephone;
public String getEmail() {
return email;
}
public String getTelephone() {
return telephone;
}
public void setEmail(String email) {
this.email = email;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/pages/index.jsp</welcome-file>
</welcome-file-list>
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:context="http://www.springframework.org/schema/context"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="pl.ivmx.contact" />
<!-- <bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="messages_en.properties" />
<property name="defaultEncoding" value="UTF-8" />
</bean> -->
<import resource="commonContext.xml" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="userTestDao" class="pl.ivmx.dao.impl.UserTestDaoImpl">
<!-- <property name="dataSource" ref="dataSource" /> -->
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" >
<!-- class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> -->
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="META-INF/hibernate.cfg.xml" />
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<!-- <property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>pl.ivmx.model.UserTest</value>
</list>
</property> -->
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
dispatcher-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:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" /> -->
<bean id="viewResolver" 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 id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="urlMap">
<map>
<entry key="/index.do"> <ref bean="index" /></entry>
<entry key="/registration.do"> <ref bean="registration" /></entry>
<entry key="/usertestlist.do"> <ref bean="usertest" /></entry>
<entry key="/contact.do"> <ref bean="contact" /></entry>
</map>
</property>
</bean>
<bean id="index" class="pl.ivmx.web.IndexController"/>
<bean id="registrationValidator" class="pl.ivmx.validation.RegistrationValidator" />
<bean id="registration" class="pl.ivmx.web.RegistrationFormController" >
<property name="commandName"><value>userTest</value></property>
<property name="commandClass"><value>pl.ivmx.model.UserTest</value></property>
<property name="validator"><ref local="registrationValidator"/></property>
<property name="formView"><value>registration</value></property>
<property name="successView"><value>registrationsuccess</value></property>
<property name="userTestDao"><ref bean="userTestDao"/></property>
</bean>
<bean id="usertest" class="pl.ivmx.web.UserTestController">
<property name="userTestDao"><ref bean="userTestDao"/></property>
</bean>
<bean id="contact" class="pl.ivmx.contact.controller.ContactController">
</bean>
<bean id="contactService" class="pl.ivmx.contact.service.ContactServiceImpl">
</bean>
<bean id="contactDAO" class="pl.ivmx.contact.dao.ContactDAOImpl">
</bean>
</beans>
It looks like a NullPointerException thrown in the method here:
#RequestMapping("/contact")
public String listContacts(Map<String, Object> map) {
map.put("contact", new Contact());
map.put("contactList", contactService.listContact());
return "/contact";
}
I would debug and check that contactService has been autowired correctly.
The null pointer is line 26, if that is the line containing contactService.listContact() then contactService is null. If it is the line above then the map is null.
I am not sure but try adding:
<context:component-scan base-package="pl.ivmx.contact" />
to the dispatcher-servlet.xml as well, it could be that the annotation isnt getting processed
you are returning "/contact" there in the method as a view to be shown:
#RequestMapping("/contact")
public String listContacts(Map<String, Object> map) {
map.put("contact", new Contact());
map.put("contactList", contactService.listContact());
return "/contact"; // <---- here!
}
This means that you should have a view named /contact defined somewhere, but I don't see it. You need to have a view that corresponds with the value you're defining.
You probably want to return a value like "contact" instead of "/contact" and then have contact.jsp in the webapp/WEB-INF/views folder (assuming you use maven standard directory layout).
I don't see anything obvious ... could sessionFactory be null? Should be easy to find, tho. Step through the code in the debugger.
I think you are missing to add the contactService bean to your applicationContext.xml
try adding the below to tags
<bean id="contactService" class="pl.ivmx.contact.service.ContactServiceImpl">
<property name="contactDAO" ref="contactDAO" />
</bean>
<bean id="contactDAO" class="pl.ivmx.contact.dao.ContactDAOImpl" />

Categories