Spring dataSource return null - java

I'm trying to connect MySQL database with Spring. And I also want to use DataSource setter method with #Autowired. Every time I run the code, DataSource always return as null.
Error:
HTTP Status 500 - Request processing failed; nested exception is java.lang.NullPointerException
Can someone show me whats wrong with my code? Please find below my code.
CustomerController.java
package com.springapp.controller;
import com.springapp.beans.Customer;
import com.springapp.service.CustomerService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class CustomerController {
private CustomerService customerService;
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView index() {
ModelAndView mv = new ModelAndView("index");
return mv;
}
#RequestMapping(value = "/listCustomers", method = RequestMethod.GET)
public ModelAndView ListCustomer() {
ModelAndView mv = new ModelAndView("customers");
Customer customer = customerService.findCustomerById(1);
mv.addObject("customer", customer);
return mv;
}
}
Customer.java
package com.springapp.beans;
public class Customer {
private int id;
private String firstName;
private String lastName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
CustomerDAO.java
package com.springapp.dao;
import com.springapp.beans.Customer;
public interface CustomerDAO {
public Customer findCustomerById(int customerId);
}
CustomerService
package com.springapp.service;
import com.springapp.beans.Customer;
import com.springapp.dao.CustomerDAO;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
#Repository
public class CustomerService implements CustomerDAO {
private DataSource dataSource;
#Autowired
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
#Override
public Customer findCustomerById(int customerId) {
String sql = "SELECT * FROM CUSTOMER WHERE CUST_ID = 1";
Customer customer = new Customer();
Connection conn = null;
try {
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
customer.setFirstName(rs.getString("first_name"));
customer.setLastName(rs.getString("last_name"));
}
rs.close();
ps.close();
return customer;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/testjavadb" />
<property name="username" value="root" />
<property name="password" value="" />
</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: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.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.springapp" />
<mvc:annotation-driven />
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
Error Log
HTTP Status 500 - Request processing failed; nested exception is java.lang.NullPointerException
type Exception report
message Request processing failed; nested exception is java.lang.NullPointerException
description The server encountered an internal error that prevented it from fulfilling this request.
Exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:973)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.NullPointerException
com.springapp.controller.CustomerController.ListCustomer(CustomerController.java:28)
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:497)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:214)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:690)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.54 logs.

In your CustomerController class, try changing this line:
private CustomerService customerService;
to:
#Autowired
private CustomerService customerService;
or you can auto-wire it via setter or constructor injection, if you like.

Related

Spring 4.3.0.RELEASE + Hibernate 5.2.0.Final - Could not obtain transaction-synchronized Session for current thread

Hi,
I got this error and i can`t figure why? all of the defintions in there place and still i have this error while i trying to insert data to my DB.
the "tx:annotation-driven" is in the appconfig-data.xml
I call the add function from "UserController"
What could be the reason it does not work?
Error log:
יול 08, 2016 1:06:23 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [searcher] in context with path [/Searcher] threw exception [Request processing failed; nested exception is org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread] with root cause
org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
at org.springframework.orm.hibernate5.SpringSessionContext.currentSession(SpringSessionContext.java:133)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:454)
at com.searcher.dao.EcommerceImp.add(EcommerceImp.java:28)
at com.searcher.controller.UserController.registration(UserController.java:42)
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.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:115)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:112)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:169)
at
Classes
** UserController.java"
package com.searcher.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.searcher.dao.RoleDAO;
import com.searcher.entity.RoleEntity;
import com.searcher.entity.UserEntity;
import com.searcher.service.SecurityService;
import com.searcher.service.UserService;
import com.searcher.validator.UserValidator;
#Controller
public class UserController {
#Autowired
private UserService userService;
#Autowired
private SecurityService securityService;
#Autowired
private UserValidator userValidator;
#Autowired
RoleDAO roleDAO;
#RequestMapping(value = "/registration", method = RequestMethod.GET)
public String registration(Model model) {
model.addAttribute("userForm", new UserEntity());
try {
// Creatinw Role Entity
RoleEntity roleUser = new RoleEntity();
RoleEntity roleAdmin = new RoleEntity();
roleUser.setName("ROLE_USER");
roleAdmin.setName("ROLE_ADMIN");
roleDAO.add(roleUser);
roleDAO.add(roleAdmin);
} catch (Exception e) {
// TODO Auto-generated catch block
throw e;
}
return "registration";
}
#RequestMapping(value = "/registration", method = RequestMethod.POST)
public String registration(#ModelAttribute("userForm") UserEntity userForm, BindingResult bindingResult, Model model) {
userValidator.validate(userForm, bindingResult);
if (bindingResult.hasErrors()) {
return "registration";
}
userService.add(userForm);
securityService.autologin(userForm.getName(), userForm.getPasswordConfirm());
return "redirect:/welcome";
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Model model, String error, String logout) {
if (error != null)
model.addAttribute("error", "Your username and password is invalid.");
if (logout != null)
model.addAttribute("message", "You have been logged out successfully.");
return "login";
}
#RequestMapping(value = {"/", "/welcome"}, method = RequestMethod.GET)
public String welcome(Model model) {
return "welcome";
}
}
UserEntity.java
package com.searcher.entity;
import java.util.List;
import java.util.Set;
import javax.persistence.*;
#Entity
#Table(name="user")
public class UserEntity {
#Id
#Column(name="User_Id")
#GeneratedValue
private long Id;
#Column(name="Name")
private String Name;
#Column(name="Password")
private String Password;
#Column(name="Password_Confirm")
private String passwordConfirm;
#Column(name="Phone")
private String Phone;
#Column(name="Email")
private String Email;
#ElementCollection(targetClass=RoleEntity.class)
private Set<RoleEntity> roles;
#ManyToMany
#JoinTable(name = "user_role", joinColumns = #JoinColumn(name = "user_id"), inverseJoinColumns = #JoinColumn(name = "role_id"))
public Set<RoleEntity> getRoles() {
return roles;
}
public void setRoles(Set<RoleEntity> roles) {
this.roles = roles;
}
public String getPasswordConfirm() {
return passwordConfirm;
}
public void setPasswordConfirm(String passwordConfirm) {
this.passwordConfirm = passwordConfirm;
}
public long getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
Phone = phone;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
#Override
public String toString(){
return "Id = " + Id + ", Name = " + Name + ", Password = " + Password + ", Phone = " + Phone + ", Email = " + Email;
}
}
RoleEntity
package com.searcher.entity;
import java.util.Set;
import javax.persistence.*;
#Entity
#Table(name = "role")
public class RoleEntity {
#Id
#GeneratedValue
#Column(name="Id")
private Long Id;
#Column(name="Name")
private String Name;
#ElementCollection(targetClass=UserEntity.class)
private Set<UserEntity> users;
public Long getId() {
return Id;
}
public void setId(Long id) {
this.Id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
this.Name = name;
}
#ManyToMany(mappedBy = "roles")
public Set<UserEntity> getUsers() {
return users;
}
public void setUsers(Set<UserEntity> users) {
this.users = users;
}
}
DAO
UserDAOImp
package com.searcher.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.searcher.entity.UserEntity;
#Repository
public class UserImp implements UserDAO{
private static final Logger logger = LoggerFactory.getLogger(UserDAO.class);
#Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
#Override
public void add(UserEntity user) {
this.sessionFactory.getCurrentSession().persist(user);
logger.info("UserEntity saved successfully, UserEntity Details="+user);
}
#Override
public void edit(UserEntity user) {
this.sessionFactory.getCurrentSession().update(user);
logger.info("UserEntity updated successfully, UserEntity Details="+user);
}
#Override
public void deleteById(int id) {
UserEntity userToDelete = getUserById(id);
this.sessionFactory.getCurrentSession().delete(userToDelete);
logger.info("UserEntity deleted successfully, UserEntity Details="+userToDelete);
}
#Override
public UserEntity getUserById(int id) {
UserEntity userReturn = (UserEntity)this.sessionFactory.getCurrentSession().get(UserEntity.class, id);
logger.info("UserEntity founded successfully, UserEntity Details="+userReturn);
return userReturn;
}
#Override
public UserEntity getUserByName(String name) {
try{
UserEntity userReturn =
(UserEntity)this.sessionFactory.getCurrentSession().createQuery("from user where Name ='" + name + "'");
if (userReturn != null){
logger.info("UserEntity founded successfully, UserEntity Details="+userReturn);
}
else{
logger.info("UserEntity Not found with Name= "+userReturn);
}
return userReturn;
}catch (Exception ex){
}
return null;
}
#SuppressWarnings({ "unchecked", "deprecation" })
#Override
public List<UserEntity> getAllUser() {
List<UserEntity> userList = this.sessionFactory.getCurrentSession().createQuery("from user").list();
logger.info("List<UserEntity> upload successfully, List<UserEntity> Details="+userList.toString());
return userList;
}
}
RoleDAOIMP
package com.searcher.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.searcher.entity.RoleEntity;
#Repository
public class RoleImp implements RoleDAO {
private static final Logger logger = LoggerFactory.getLogger(RoleDAO.class);
#Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
#Override
public void add(RoleEntity role) {
this.sessionFactory.getCurrentSession().persist(role);
logger.info("RoleEntity saved successfully, RoleEntity Details="+role);
}
#Override
public void edit(RoleEntity role) {
this.sessionFactory.getCurrentSession().update(role);
logger.info("RoleEntity updated successfully, RoleEntity Details="+role);
}
#Override
public void deleteById(int id) {
RoleEntity roleToDelete = getRoleById(id);
this.sessionFactory.getCurrentSession().delete(roleToDelete);
logger.info("RoleEntity deleted successfully, RoleEntity Details="+roleToDelete);
}
#Override
public RoleEntity getRoleById(int id) {
RoleEntity roleReturn = (RoleEntity)this.sessionFactory.getCurrentSession().get(RoleEntity.class, id);
logger.info("RoleEntity founded successfully, RoleEntity Details="+roleReturn);
return roleReturn;
}
#Override
public RoleEntity getRoleByName(String name) {
RoleEntity roleReturn =
(RoleEntity)this.sessionFactory.getCurrentSession().createNamedQuery("from role where Name =" + name);
logger.info("RoleEntity founded successfully, RoleEntity Details="+roleReturn);
return roleReturn;
}
#SuppressWarnings({ "unchecked", "deprecation" })
#Override
public List<RoleEntity> getAllRole() {
List<RoleEntity> roleList = this.sessionFactory.getCurrentSession().createQuery("from role").list();
logger.info("List<RoleEntity> upload successfully, List<RoleEntity> Details="+roleList.toString());
return roleList;
}
}
UserServiceImp
package com.searcher.service;
import java.util.HashSet;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.searcher.dao.RoleDAO;
import com.searcher.dao.UserDAO;
import com.searcher.entity.UserEntity;
#Service("userService")
public class UserServiceImp implements UserService{
#Autowired
private UserDAO userDAO;
#Autowired
private RoleDAO roleDAO;
//#Autowired(required=true)
#Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
public UserDAO getUserDAO() {
return userDAO;
}
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
public RoleDAO getRoleDAO() {
return roleDAO;
}
public void setRoleDAO(RoleDAO roleDAO) {
this.roleDAO = roleDAO;
}
public BCryptPasswordEncoder getbCryptPasswordEncoder() {
return bCryptPasswordEncoder;
}
public void setbCryptPasswordEncoder(BCryptPasswordEncoder bCryptPasswordEncoder) {
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}
#Override
#Transactional
public void add(UserEntity user) {
try {
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
user.setRoles(new HashSet<>(roleDAO.getAllRole()));
this.userDAO.add(user);
} catch (Exception e) {
// TODO: handle exception
}
}
#Override
#Transactional
public void edit(UserEntity user) {
this.userDAO.edit(user);
}
#Override
#Transactional
public void deleteById(int id) {
this.userDAO.deleteById(id);
}
#Override
#Transactional
public UserEntity getUserById(int id) {
return this.userDAO.getUserById(id);
}
#Override
#Transactional
public UserEntity getUserByName(String name) {
return this.userDAO.getUserByName(name);
}
#Override
#Transactional
public List<UserEntity> getAllUser() {
return this.userDAO.getAllUser();
}
}
RoleServiceImpl
package com.searcher.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.searcher.dao.RoleDAO;
import com.searcher.entity.RoleEntity;
public class RoleServiceImp implements RoleService {
#Autowired
private RoleDAO roleDAO;
public RoleDAO getRoleDAO() {
return roleDAO;
}
public void setRoleDAO(RoleDAO roleDAO) {
this.roleDAO = roleDAO;
}
#Override
#Transactional
public void add(RoleEntity role) {
this.roleDAO.add(role);
}
#Override
#Transactional
public void edit(RoleEntity role) {
this.roleDAO.edit(role);
}
#Override
#Transactional
public void deleteById(int id) {
this.roleDAO.deleteById(id);
}
#Override
#Transactional
public RoleEntity getRoleById(int id) {
return this.roleDAO.getRoleById(id);
}
#Override
#Transactional
public RoleEntity getRoleByName(String name) {
return this.roleDAO.getRoleByName(name);
}
#Override
#Transactional
public List<RoleEntity> getAllRole() {
return (List<RoleEntity>)this.roleDAO.getAllRole();
}
}
This is the folowing configuration files:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<display-name>Searcher</display-name>
<!-- Location of Java #Configuration classes that configure the components that makeup this application -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/appconfig-root.xml</param-value>
</context-param>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>searcher</servlet-name>
<servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>searcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
-->
<!--
<servlet-mapping>
<servlet-name>searcher</servlet-name>
<url-pattern>/welcome.jsp</url-pattern>
<url-pattern>/welcome.html</url-pattern>
<url-pattern>*.html</url-pattern>
</servlet-mapping>-->
</web-app>
appconfig-root.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns="http://www.springframework.org/schema/beans"
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">
<import resource="appconfig-mvc.xml"/>
<import resource="appconfig-data.xml"/>
<import resource="appconfig-security.xml"/>
<!-- Scans within the base package of the application for #Component classes to configure as beans -->
<context:component-scan base-package="com.searcher.*"/>
<!--<context:property-placeholder location="classpath:application.properties"/>-->
</beans>
appconfig-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.1.xsd">
<http auto-config="true">
<intercept-url pattern="/" access="hasRole('ROLE_USER')"/>
<intercept-url pattern="/welcome" access="hasRole('ROLE_USER')"/>
<form-login login-page="/login" default-target-url="/welcome" authentication-failure-url="/login?error" username-parameter="username" password-parameter="password"/>
<logout logout-success-url="/login?logout" />
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="userDetailsServiceImpl">
<password-encoder ref="encoder"></password-encoder>
</authentication-provider>
</authentication-manager>
<beans:bean id="userDetailsServiceImpl" class="com.searcher.service.UserDetailsServiceImpl"></beans:bean>
<beans:bean id="encoder"
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
<beans:constructor-arg name="strength" value="11"/>
</beans:bean>
</beans:beans>
appconfig-data.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Configure the data source bean -->
<!-- DataSource -->
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url"
value="jdbc:mysql://localhost:3306/SearcherDB" />
<beans:property name="username" value="root" />
<beans:property name="password" value="root" />
</beans:bean>
<!-- Hibernate 5 SessionFactory Bean definition -->
<beans:bean id="hibernate5AnnotatedSessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="annotatedClasses">
<beans:list>
<beans:value>com.searcher.entity.RoleEntity</beans:value>
<beans:value>com.searcher.entity.UserEntity</beans:value>
</beans:list>
</beans:property>
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</beans:prop>
<beans:prop key="hibernate.show_sql">true</beans:prop>
<beans:prop key="hibernate.format_sql">true</beans:prop>
<!-- <beans:prop key="hibernate.hbm2ddl.auto">create</beans:prop> -->
</beans:props>
</beans:property>
</beans:bean>
<!-- User -->
<beans:bean id="userDAO" class="com.searcher.dao.UserImp">
<beans:property name="sessionFactory" ref="hibernate5AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="userService" class="com.searcher.service.UserServiceImp">
<beans:property name="userDAO" ref="userDAO"></beans:property>
</beans:bean>
<!-- Role -->
<beans:bean id="roleDAO" class="com.searcher.dao.RoleImp">
<beans:property name="sessionFactory" ref="hibernate5AnnotatedSessionFactory" />
</beans:bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- Configure the transaction manager bean -->
<beans:bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="hibernate5AnnotatedSessionFactory" />
</beans:bean>
</beans>
appconfig-mvc.xml
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<mvc:annotation-driven/>
<mvc:resources mapping="/resources/**" location="/resources/"/>
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>classpath:validation</value>
</list>
</property>
</bean>
<!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass">
<value>org.springframework.web.servlet.view.JstlView</value>
</property>
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
You are using non transactional daos in your UserController.registration method:
roleDAO.add(roleUser);
roleDAO.add(roleAdmin);
Use RoleServiceImpl instead.

org.springframework.beans.factory.BeanCreationException:

I am getting following exception,please help to resolve this ?
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.dao.UserDAO com.controller.UserController.userDAO; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDAOImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.dao.UserDAOImpl.sessionFactory; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.hibernate.SessionFactory] 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)}
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:609)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:469)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:631)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:588)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:645)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:508)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:449)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:133)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
root cause
org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.dao.UserDAO com.controller.UserController.userDAO; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDAOImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.dao.UserDAOImpl.sessionFactory; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.hibernate.SessionFactory] 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)}
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:506)
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:609)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:469)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:631)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:588)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:645)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:508)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:449)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:133)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
Respective java codes are as below -
UserDAO
package com.dao;
import java.util.List;
import com.entity.UserDetails;
public interface UserDAO {
public List<UserDetails> getUserProfileDetails();
public int saveUserDetails(UserDetails userDetails);
public UserDetails authenticateUser(String email,String password);
public void closeSessionObjects();
}
UserDAOImpl
package com.dao;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.dao.UserDAO;
import com.entity.UserDetails;
#Component
#Transactional(readOnly = true)
public class UserDAOImpl implements UserDAO {
private static Logger logger = Logger.getLogger(UserDAOImpl.class);
#Autowired
private SessionFactory sessionFactory;
Session session = null;
private void assignSessionLocalVariable(){
if(session == null || !session.isOpen()){
try{
session = sessionFactory.openSession();
}catch(Exception e){session = null;}
}
}
#Override
public List<UserDetails> getUserProfileDetails() {
List<UserDetails> details=null;
if(session!=null){
try{
Query query = session.createQuery("from user");
details = query.list();
}catch(Exception e)
{
logger.error("########### Exception occured ########## "+e+" ");
}
}
return details;
}
#Override
public int saveUserDetails(UserDetails userDetails){
int saved=1;
assignSessionLocalVariable();
try{
Transaction tx=session.beginTransaction();
session.save(userDetails);
tx.commit();
saved=0;
logger.info("#### Details saved successfuly #####");
}catch(Exception e){
logger.error("### Exception occured in UserDAOImpl class #### "+e+"");
}
return saved;
}
#Override
public UserDetails authenticateUser(String email, String pwd) {
// TODO Auto-generated method stub
System.out.println("##### UserDAOImple authenticateuser started #####");
assignSessionLocalVariable();
logger.info("### Authentication of the user in progress ####");
UserDetails users = null;
if(session!=null){
try{
Query qry = session.createQuery ("from user hu where hu.email = :email and hu.password = :password");
qry.setParameter ("email", email);
qry.setParameter ("password", pwd);
qry.setMaxResults(1);
users = (UserDetails)qry.uniqueResult();
}catch(Exception e){
users = null;
System.out.println("UserDAOImpl exception in getting unique result["+e+"] ");
logger.error("UserDAOImpl exception in getting unique result["+e+"]");
}
}//if(session!=null)
return users;
}
public void closeSessionObjects(){
if(null != session) session.clear();//close();
//if(null != sessionFactory) sessionFactory.close();
}
}
UsedDetails.java
package com.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name="user",catalog="test")
public class UserDetails implements java.io.Serializable{
private int id;
private String firstName;
private String lastName;
private int age;
private Date creationTime;
private Date lastModTime;
private String password;
private String email;
public UserDetails(){}
public UserDetails(String email){
this.email=email;
}
#Id
#Column(name="ID", unique = true, nullable = false)
public int getId() {
return id;
}
public void setId(int id){
this.id = id;
}
#Column(name="FIRST_NAME")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name="LAST_NAME")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Column(name="AGE")
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "CREATION_TIME", nullable = false, length = 19)
public Date getCreationTime() {
return creationTime;
}
public void setCreationTime(Date creationTime) {
this.creationTime = creationTime;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "LAST_MOD_TIME", nullable = false, length = 19)
public Date getLastModTime() {
return lastModTime;
}
public void setLastModTime(Date lastModTime) {
this.lastModTime = lastModTime;
}
#Column(name="PASSWORD")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Column(name="EMAIL")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
UserController.java
package com.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.dao.UserDAO;
import com.entity.UserDetails;
#Controller
public class UserController {
private static Logger logger = Logger.getLogger(UserController.class);
String errForward = "user.error", forward = null;
#Autowired
UserDAO userDAO;
#Autowired
UserDetails ud=null;;
#RequestMapping("/register")
public ModelAndView registerPage() {
logger.info("## Registration page forward #####");
return new ModelAndView("user.registration");
}
#RequestMapping("/registerUser")
public ModelAndView registerUser(HttpServletRequest request) {
logger.info("### Inside registeration controller ####");
int isSave=0;
Date creation_time=null,lastModTime=null;
String fName=request.getParameter("fName");
fName=(fName.equals(""))?"":fName.trim();
String lName=request.getParameter("lName");
lName=(lName.equals(""))?"":lName.trim();
int age=Integer.parseInt(request.getParameter("age"));
age=(age==0)?0:age;
String email=request.getParameter("email");
email=(email.equals(""))?"":email.trim();
String pswd=request.getParameter("pswd");
pswd=(pswd.equals(""))?"":pswd.trim();
Date date=new Date();
//creation_time=dt.getDate();
ud.setFirstName(fName);
ud.setLastName(lName);
ud.setAge(age);
ud.setPassword(pswd);
ud.setEmail(email);
ud.setCreationTime(creation_time);
ud.setLastModTime(lastModTime);
try{
isSave=userDAO.saveUserDetails(ud);
if (isSave==0){
System.out.println("%%% Successfully saved the user ::::"+isSave);
logger.info("Successfully saved the data :::"+isSave);
forward="user.registrationUserSuccess";
}
}catch(Exception e){
logger.error("##### Error while saving use details #####"+e);
return new ModelAndView(forward);
}
return new ModelAndView(forward);
}
#RequestMapping("/login")
public ModelAndView addStudent(HttpServletRequest request) {
logger.info("### Login in progress ####");
String email=request.getParameter("email");
email=(email.equals(""))?"":email.trim();
String pswd=request.getParameter("pswd");
pswd=(pswd.equals(""))?"":pswd.trim();
String login=request.getParameter("login");
login = (null != login)?login:"";
logger.info("### User login for ::: ["+email+"]:::: ######");
HttpSession httpSession = request.getSession();
if(null!=login)ud= userDAO.authenticateUser(email, pswd);
if(null!=ud){
httpSession.setAttribute("isActiveUser", ud);
forward = "user.profile";
}else forward = errForward;
return new ModelAndView(forward);
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" id="WebApp_ID" version="2.4">
<display-name>Spring User</display-name>
<servlet>
<servlet-name>User</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>User</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/jsp/home.jsp</welcome-file>
</welcome-file-list>
<session-config>
<session-timeout>60</session-timeout>
</session-config>
</web-app>
User-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-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-3.1.xsd">
<mvc:annotation-driven/>
<context:annotation-config/>
<context:component-scan base-package="com.controller" />
<context:component-scan base-package="com.dao" />
<context:component-scan base-package="com.entity" />
<!-- title defining -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles2.TilesView
</value>
</property>
</bean>
<!-- defining title file location -->
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
<import resource="db-config.xml" />
</beans>
db-config.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:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<bean id="dbPropertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>/WEB-INF/configuration.properties</value>
</list>
</property>
</bean>
<!-- Database Properties -->
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"
p:driverClass="${jdbc.driver.className}"
p:jdbcUrl="${jdbc.url}"
p:user="${jdbc.username}"
p:password="${jdbc.password}"
/>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.hibernate.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="packagesToScan" value="com.entity" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
When I try to run this code I am getting exception that I have posted. Autowired injection is not happening. What is the problem ?
Take a close look at the Exception, It says
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.
It looks like you are not creating sessionFactory bean. Make sure you have sessionFactory added in you spring configuration
For Example :
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
p:dataSource-ref="dataSource"
p:configLocation="${hibernate.config}"
/>

Migration from ObjectDB to MySQL in Spring

I've been using objectDB as a database in my Spring application, yet it is only free for up to 10 tables, so i've tried to migrate to MySQL. When I look into database the tables are created, but when I try to persist I get the NullPointerException. Here are my configuration files:
persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="cinemabookPU" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>cinemaDbCon</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.SunOneJtaPlatform" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
</persistence>
spring-servlet.xml:
<?xml version="1.0" encoding="windows-1252"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!-- Use #Component annotations for bean definitions -->
<context:component-scan base-package="cinema"/>
<!-- Use #Controller annotations for MVC controller definitions -->
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:annotation-driven />
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.glassfish.GlassFishLoadTimeWeaver"/>
</property>
</bean>
<tx:jta-transaction-manager />
<tx:annotation-driven />
<bean class=
"org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/"/>
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<import resource="/spring-security.xml" />
</beans>
Model City:
package cinema.model;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class City implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String name;
protected City() {
}
public City(Long id, String name) {
this.id = id;
this.name = name;
}
public City(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return name;
}
}
CityService.java:
package cinema.services;
import cinema.model.City;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
public interface CityService {
// Stores a new city:
#Transactional
public void persist(City city);
// Retrieves all the citys:
public List<City> getAllCities();
public City getCityById(Long id);
public void deleteAllCities();
}
CityServiceImpl.java:
package cinema.services.impl;
import cinema.services.CityService;
import cinema.model.City;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
#Component
public class CityServiceImpl implements CityService {
// Injected database connection:
#PersistenceContext(unitName="cinemabookPU")
private EntityManager em;
public EntityManager getEm() {
return em;
}
public void setEm(EntityManager em) {
this.em = em;
}
// Stores a new city:
#Transactional
public void persist(City city) {
em = getEm();
System.out.println("EM "+em);
em.persist(city);
}
// Retrieves all the citys:
public List<City> getAllCities() {
TypedQuery<City> query = em.createQuery(
"SELECT c FROM City c", City.class);
return query.getResultList();
}
public City getCityById(Long id) {
TypedQuery<City> query = em.createQuery(
"SELECT c FROM City c WHERE c.id = :id", City.class);
return query.setParameter("id", id).getSingleResult();
}
#Transactional(propagation = Propagation.REQUIRED)
public void deleteAllCities() {
TypedQuery<City> query = em.createQuery(
"DELETE FROM City", City.class);
query.executeUpdate();
}
}
Any help will be greatly appreciated.

Using JPA with hibernate inserting data in database.. but issue in inserting data

I am using JPA with Hibernate and unable to insert data ..
the serviceImpl class:
package home;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import com.order.OrderBook;
public class OrderServiceImpl implements OrderService {
#Override
public void add(OrderBook orderbook) {
EntityManagerFactory emf=Persistence.createEntityManagerFactory("PU");
System.out.println("in Get Users");
EntityManager em=emf.createEntityManager();
EntityTransaction et=em.getTransaction();
et.begin();
String timeStamp =
new SimpleDateFormat("dd-MM-yyyy:HH.mm.ss").
format(new Timestamp(System.currentTimeMillis()));
orderbook.setOrder_date(timeStamp);
em.persist(orderbook);
System.out.println("after persist");
et.commit();
System.out.println("Inserted");
}
}
OrderBook.java
package com.order;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "order_book")
public class OrderBook {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int order_id;
private int client_id;
private int broker_id;
private String order_date;
private int stock_id;
private int price_per_share;
private int no_of_share;
private int total_amount;
private String trade_type;
public int getOrder_id() {
return order_id;
}
public void setOrder_id(int order_id) {
this.order_id = order_id;
}
public int getClient_id() {
return client_id;
}
public void setClient_id(int client_id) {
this.client_id = client_id;
}
public int getBroker_id() {
return broker_id;
}
public void setBroker_id(int broker_id) {
this.broker_id = broker_id;
}
public String getOrder_date() {
return order_date;
}
public void setOrder_date(String order_date) {
this.order_date =order_date;
}
public int getStock_id() {
return stock_id;
}
public void setStock_id(int stock_id) {
this.stock_id = stock_id;
}
public int getPrice_per_share() {
return price_per_share;
}
public void setPrice_per_share(int price_per_share) {
this.price_per_share = price_per_share;
}
public int getNo_of_share() {
return no_of_share;
}
public void setNo_of_share(int no_of_share) {
this.no_of_share = no_of_share;
}
public int getTotal_amount() {
return total_amount;
}
public void setTotal_amount(int total_amount) {
this.total_amount = total_amount;
}
public String getTrade_type() {
return trade_type;
}
public void setTrade_type(String trade_type) {
this.trade_type = trade_type;
}
}
but while running I getting this error. upto persist() method it is being executed but it is not executing commit() method.
exception
org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.NoSuchMethodError: org.hibernate.event.PreInsertEvent.getSource()Lorg/hibernate/engine/SessionImplementor;
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:812)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:709)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:613)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:536)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
root cause
java.lang.NoSuchMethodError: org.hibernate.event.PreInsertEvent.getSource()Lorg/hibernate/engine/SessionImplementor;
org.hibernate.validator.event.ValidateEventListener.onPreInsert(ValidateEventListener.java:156)
org.hibernate.action.EntityInsertAction.preInsert(EntityInsertAction.java:178)
org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:72)
org.hibernate.engine.ActionQueue.execute(ActionQueue.java:279)
org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:263)
org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:167)
org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1027)
org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:365)
org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:53)
home.OrderServiceImpl.add(OrderServiceImpl.java:32)
com.order.web.OrderController.onSubmit(OrderController.java:31)
org.springframework.web.servlet.mvc.SimpleFormController.onSubmit(SimpleFormController.java:415)
org.springframework.web.servlet.mvc.SimpleFormController.onSubmit(SimpleFormController.java:387)
org.springframework.web.servlet.mvc.SimpleFormController.processFormSubmission(SimpleFormController.java:272)
org.springframework.web.servlet.mvc.AbstractFormController.handleRequestInternal(AbstractFormController.java:268)
org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:153)
org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:763)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:709)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:613)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:536)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.0 logs.
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="PU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.order.OrderBook</class>
<!-- <exclude-unlisted-classes /> -->
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
<property name="hibernate.connection.url" value="jdbc:oracle:thin:#localhost:1521:XE"/>
<property name="hibernate.connection.driver_class" value="oracle.jdbc.OracleDriver"/>
<property name="hibernate.connection.username" value="system"/>
<property name="hibernate.connection.password" value="newuser123#"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
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 ">
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
<bean id="orderService" class="home.OrderServiceImpl" />
<bean name="/placeOrder.htm" class="com.order.web.OrderController" p:orderService-ref="orderService"
p:formView="userForm" p:successView="userSuccess" />
</beans>

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

Categories