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}"
/>
Related
I am new to Spring and I am try to make a application for learning but I am getting problem in Autowiring,I am adding my code. I am working on spring boot.
logincontroller:
package com.cloudnexus.spring.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.cloudnexus.spring.model.Login;
import com.cloudnexus.spring.model.User;
import com.cloudnexus.spring.service.UserService;
#Controller
public class LoginController {
#Autowired
UserService userService;
#RequestMapping(value = "/loginProcess", method = RequestMethod.POST)
public ModelAndView loginProcess(HttpServletRequest request, HttpServletResponse response,
#ModelAttribute("login") Login login) {
ModelAndView mav = null;
User user = userService.validateUser(login);
if (null != user) {
mav = new ModelAndView("welcome");
mav.addObject("firstname", user.getUsername());
} else {
mav = new ModelAndView("login");
mav.addObject("message", "Username or Password is wrong!!");
}
return mav;
}
}
////
Login POJO:
package com.cloudnexus.spring.model;
public class Login {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
User Pojo :
package com.cloudnexus.spring.model;
public class User {
private String username;
private String password;
private int IsActive;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getIsActive() {
return IsActive;
}
public void setIsActive(int isActive) {
IsActive = isActive;
}
}
UserDao :
package com.cloudnexus.spring.dao;
import com.cloudnexus.spring.model.Login;
import com.cloudnexus.spring.model.User;
public interface UserDao {
User validateUser(Login login);
}
UserDaoImpl
package com.cloudnexus.spring.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import com.cloudnexus.spring.model.Login;
import com.cloudnexus.spring.model.User;
public class UserDaoImpl implements UserDao{
#Autowired
DataSource datasource;
#Autowired
JdbcTemplate jdbcTemplate;
public User validateUser(Login login) {
String sql = "select * from users where username='" + login.getUsername() + "' and password='" + login.getPassword()
+ "'";
List<User> users = jdbcTemplate.query(sql, new UserMapper());
return users.size() > 0 ? users.get(0) : null;
}
}
class UserMapper implements RowMapper<User> {
public User mapRow(ResultSet rs, int arg1) throws SQLException {
User user = new User();
user.setUsername(rs.getString("Name"));
user.setPassword(rs.getString("Password"));
user.setIsActive(rs.getInt("IsActive"));
return user;
}
}
UserService :
package com.cloudnexus.spring.service;
import com.cloudnexus.spring.model.Login;
import com.cloudnexus.spring.model.User;
public interface UserService {
User validateUser(Login login);
}
UserServiceImpl
package com.cloudnexus.spring.service;
import org.springframework.beans.factory.annotation.Autowired;
import com.cloudnexus.spring.dao.UserDao;
import com.cloudnexus.spring.model.Login;
import com.cloudnexus.spring.model.User;
public class UserServiceImpl implements UserService{
#Autowired
public UserDao userDao;
public User validateUser(Login login) {
return userDao.validateUser(login);
}
}
spring bean configuration file :
<?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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.cloudnexus.spring" />
<context:annotation-config />
<bean id="userService" class="com.cloudnexus.spring.service.UserServiceImpl">
<property name="userService" ref="userService"></property>
</bean>
<bean name="userDao" class="com.cloudnexus.spring.dao.UserDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="datasource" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="url" value=";DatabaseName=" />
<property name="username" value="" />
<property name="password" value="" />
</bean>
</beans>
#Autowired to LoginBean loginBean;
Created getter setter of LoginBean in Controller class and autowired setters;
Created constructor of Controller and autowired, as given in above code;
Below is the error which I am getting :
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'loginController': Unsatisfied dependency expressed through field 'userService': Error creating bean with name 'userService': Unsatisfied dependency expressed through field 'userDao': Error creating bean with name 'userDao' defined in ServletContext resource [/WEB-INF/springBeanConfiguration.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'dataSource' of bean class [com.cloudnexus.spring.dao.UserDaoImpl]: Bean property 'dataSource' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDao' defined in ServletContext resource [/WEB-INF/springBeanConfiguration.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'dataSource' of bean class [com.cloudnexus.spring.dao.UserDaoImpl]: Bean property 'dataSource' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService': Unsatisfied dependency expressed through field 'userDao': Error creating bean with name 'userDao' defined in ServletContext resource [/WEB-INF/springBeanConfiguration.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'dataSource' of bean class [com.cloudnexus.spring.dao.UserDaoImpl]: Bean property 'dataSource' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDao' defined in ServletContext resource [/WEB-INF/springBeanConfiguration.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'dataSource' of bean class [com.cloudnexus.spring.dao.UserDaoImpl]: Bean property 'dataSource' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:569)
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:349)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:776)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:634)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:682)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:553)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
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:312)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
java.lang.Thread.run(Thread.java:748)
Your jdbcTemplate bean expects a bean named datasource, like you have set-it-up here (in the ref=... part:
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="datasource" />
</bean>
But your datasource bean does not exist. The reason is because you have defined it as dataSource (notice the capital "S") in bean id="dataSource"
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="url" value=";DatabaseName=" />
<property name="username" value="" />
<property name="password" value="" />
</bean>
So change this to "datasource" e.g. bean id="datasource" or change the reference in your jdbcTemplate to ref="dataSource"
Also the <property name="url" value=";DatabaseName=" /> doesn't look correct, I think you miss the correct value here, ";DatabaseName=" looks wrong or incomplete.
UPDATE
Since you are using xml spring configuration, the #Autowired annotation in your UserDaoImpl and UserServiceImpl classes is unnecessary. However, the xml configuration requires that the equivalent getters/setters exist. So change your code as:
In your UserDaoImpl you do not need the dataSource bean at all, so we are removing it.
public class UserDaoImpl implements UserDao{
JdbcTemplate jdbcTemplate;
public User validateUser(Login login) {
String sql = "select * from users where username='" + login.getUsername() + "' and password='" + login.getPassword()
+ "'";
List<User> users = jdbcTemplate.query(sql, new UserMapper());
return users.size() > 0 ? users.get(0) : null;
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
}
You do need however the jdbcTemplate bean and in your xml definition you are not setting it, so update also your spring xml file to :
<bean name="userDao" class="com.cloudnexus.spring.dao.UserDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
and
public class UserServiceImpl implements UserService{
private UserDao userDao;
public User validateUser(Login login) {
return userDao.validateUser(login);
}
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}
Also you have another mistake in the spring xml configuration file. In the userService bean definition your are setting it again as a property:
<property name="userService" ref="userService"></property>
This is wrong, you should set the userDao there. Update it as:
<bean id="userService" class="com.cloudnexus.spring.service.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
WARNING: Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'registrationController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.concept.UserService com.concept.RegistrationController.userService; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.concept] for bean with name 'UserService' defined in ServletContext resource [/WEB-INF/Spring-servlet.xml]; nested exception is java.lang.ClassNotFoundException: com.concept
Can you please help what might be the cause .I am new to Spring framework
WARNING: Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'registrationController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.concept.UserService com.concept.RegistrationController.userService; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.concept] for bean with name 'UserService' defined in ServletContext resource [/WEB-INF/Spring-servlet.xml]; nested exception is java.lang.ClassNotFoundException: com.concept
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1202)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:762)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1227)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1140)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1027)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5038)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5348)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
And here is my controller
package com.concept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.concept.UserService;
import com.concept.User;
#Controller
public class RegistrationController {
#Autowired
UserService userService;
#RequestMapping("/insert")
public String inserData(#ModelAttribute User user) {
if (user != null)
userService.insertData(user);
return "result" ;
}
}
And here is user.java
package com.concept;
public class User {
private String firstName;
private String lastName;
private Integer age;
private String email;
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;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
And here is my UserDAO.java
package com.concept;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
public class UserDAO implements UserService {
#Autowired
DataSource dataSource;
public void insertData(User user) {
String sql = "INSERT INTO Enroll(first_name,last_name, age, email) VALUES (?, ?, ?,?)";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.update(sql, new Object[] { user.getFirstName(), user.getLastName(),
user.getAge(),user.getEmail() });
}
}
And here is my UserService.java
package com.concept;
public interface UserService {
public void insertData(User user);
}
And here is my Spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="com.concept" />
<!-- adding view resolver to show jsp's on browser -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="UserService" class="com.concept"/>
<!-- declare datasource bean -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#localhost:1521:XE" />
<property name="username" value="EMPLOYEE" />
<property name="password" value="pass1234" />
</bean>
</beans>
And Here is my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Spring MVC Application</display-name>
<servlet>
<servlet-name>Spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
See the root cause: nested exception is java.lang.ClassNotFoundException: com.concept
remove the line <bean id="UserService" class="com.concept"/>
because com.concept is a package not a class. also you should not mix XML and Annotation based configuration.
And add #Repository to public class UserDAO implements UserService {
But i do not understand why you DAO implements an Interface called Service
I'am using spring and hibernate.
My entity:
package com.igorgorbunov3333.core.entities.domain;
import com.igorgorbunov3333.core.entities.enums.Proceeding;
import javax.persistence.*;
import java.util.Date;
/**
* Created by Игорь on 03.04.2016.
*/
#Entity
#Table(name = "cases")
#NamedQueries({
#NamedQuery(name = "getAllCases", query = "SELECT c FROM Case c JOIN FETCH c.client JOIN FETCH c.firstInstance " +
"JOIN FETCH c.secondInstance JOIN FETCH c.thirdInstance JOIN FETCH c.category")
})
public class Case {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "case_number")
private String caseNumber;
#ManyToOne
#JoinColumn(name = "client_id")
private Client client;
#OneToOne
#JoinColumn(name = "first_instance_id")
private FirstInstance firstInstance;
#OneToOne
#JoinColumn(name = "second_instance_id")
private SecondInstance secondInstance;
#OneToOne
#JoinColumn(name = "third_instance_id")
private ThirdInstance thirdInstance;
#Enumerated(EnumType.ORDINAL)
private Proceeding proceeding;
#Temporal(TemporalType.DATE)
#Column(name = "closing_date")
private Date closingDate;
#ManyToOne
#JoinColumn(name = "category_id")
private Category category;
private float price;
public long getId() {
return id;
}
public String getCaseNumber() {
return caseNumber;
}
public Client getClient() {
return client;
}
public FirstInstance getFirstInstance() {
return firstInstance;
}
public SecondInstance getSecondInstance() {
return secondInstance;
}
public ThirdInstance getThirdInstance() {
return thirdInstance;
}
public Proceeding getProceeding() {
return proceeding;
}
public Date getClosingDate() {
return closingDate;
}
public Category getCategory() {
return category;
}
public float getPrice() {
return price;
}
public void setId(long id) {
this.id = id;
}
public void setCaseNumber(String caseNumber) {
this.caseNumber = caseNumber;
}
public void setClient(Client client) {
this.client = client;
}
public void setFirstInstance(FirstInstance firstInstance) {
this.firstInstance = firstInstance;
}
public void setSecondInstance(SecondInstance secondInstance) {
this.secondInstance = secondInstance;
}
public void setThirdInstance(ThirdInstance thirdInstance) {
this.thirdInstance = thirdInstance;
}
public void setProceeding(Proceeding proceeding) {
this.proceeding = proceeding;
}
public void setClosingDate(Date closingDate) {
this.closingDate = closingDate;
}
public void setCategory(Category category) {
this.category = category;
}
public void setPrice(float price) {
this.price = price;
}
}
spring-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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd" >
<!--#Transaction annotation support -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!--Scanning components in base-package (look for annotations) -->
<context:component-scan base-package="com.igorgorbunov3333"/>
<!--Activates various annotations to be detected in bean classes: Spring's #Required and #Autowired and so on-->
<context:annotation-config/>
<!--Обеспечивает работу с транзакциями в Spring -->
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="emf"/>
</bean>
<!-- Datasource. Источник данных - база MySQL -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/database" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<!-- EntityManagerFactory -->
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<!--Поставщик данных - hibernate-->
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<!--поиск сущностей в этом пакете-->
<property name="packagesToScan"
value="com.igorgorbunov3333"/>
<!--детали конфигурации поставщика постоянства (hibernate) -->
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQL5Dialect
</prop>
<prop key="hibernate.max_fetch_depth">3</prop>
<prop key="hibernate.jdbc.fetch_size">50</prop>
<prop key="hibernate.jdbc.batch_size">10</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
</beans>
Here I'm getting NullPointerException:
public Case findById(long id) {
return entityManager.find(Case.class, id);
}
I sure to you - id is correct, but entity can't be found. But when I'm getting all entities all fine:
public List<Case> findAll() {
Query query = entityManager.createNamedQuery("getAllCases");
return query.getResultList();
}
What is the reason?
Full track of NPE:
09-Oct-2016 12:40:41.650 SEVERE [http-nio-8080-exec-7] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [ShowSingleCase] in context with path [] threw exception
java.lang.NullPointerException
at com.igorgorbunov3333.core.entities.service.impl.CaseServiceImpl.findById(CaseServiceImpl.java:32)
at com.igorgorbunov3333.web.servlet.display.single.ShowSingleCase.doGet(ShowSingleCase.java:29)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.logging.log4j.web.Log4jServletFilter.doFilter(Log4jServletFilter.java:71)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:522)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:1096)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:760)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1480)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
My CaseServiceImpl:
package com.igorgorbunov3333.core.entities.service.impl;
import com.igorgorbunov3333.core.entities.domain.Case;
import com.igorgorbunov3333.core.entities.enums.CaseStatus;
import com.igorgorbunov3333.core.entities.service.api.CaseService;
import com.igorgorbunov3333.core.util.DateUtil;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.*;
/**
* Created by Игорь on 27.07.2016.
*/
#Repository
#Service("CaseService")
public class CaseServiceImpl implements CaseService {
#PersistenceContext
private EntityManager entityManager;
public Case findById(long id) {
return entityManager.find(Case.class, id);
}
}
Servlet:
package com.igorgorbunov3333.web.servlet.display.single;
import com.igorgorbunov3333.core.entities.domain.Case;
import com.igorgorbunov3333.core.entities.service.api.CaseService;
import com.igorgorbunov3333.core.entities.service.impl.CaseServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static com.igorgorbunov3333.web.util.Views.SINGLE_CASE_PAGE;
/**
* Created by Игорь on 09.08.2016.
*/
#WebServlet(name = "ShowSingleCase", urlPatterns = "/showSingleCase")
public class ShowSingleCase extends HttpServlet {
private CaseService caseService = new CaseServiceImpl();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
long id = Long.valueOf(request.getParameter("caseID"));
Case c = caseService.findById(id);
request.setAttribute("case", c);
request.getRequestDispatcher(SINGLE_CASE_PAGE).forward(request, response);
}
}
Your problem is in this line:
private CaseService caseService = new CaseServiceImpl();
That's not how dependency injection works. You're instantiating your CaseService object manually. In this case framework won't inject any dependencies so your private EntityManager entityManager; field will be null. Instead you have to annotate your caseService field with #Autowired annotation. That will tell Spring to inject the bean from context:
#Autowired
private CaseService caseService;
The only thing that can be null (is not primitive) on the line you stated that would cause a problem is entityManager, so you're looking for the underlying reason for this, which I don't see in the code you posted.
As you are creating CaseServiceImpl class object by yourself in your servlet class, entityManager object is not autowire automatically by spring and that is the reason you are getting NullPointerException. either you should autowire service class object into servlet class so that spring will resolve entitymanager dependency by itself and provide you fully configured service object or you should set entity manager object into your service class while creating its object in servlet.
I am new to spring. I was trying to integrate spring with hibernate but
I am not able to get my entity class Employee using packagesToScan, before this I tried annnotatedClasses as well that too didn't work, I also tried wildcards (com.sfb.**.*) with packagesToScan but no luck yet. FYI I am using javax.persistence.Entity so not an import issue too. Below are my spring.xml file and other along with stacktrace:
Spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.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.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/sonoo"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="AnnotatedSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.sfb.model.*" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="employeeDao" class ="com.sfb.dao.EmployeeDaoImpl">
<property name="sessionFactory" ref="AnnotatedSessionFactory"/>
</bean>
<bean id="dateFormat" class="java.text.SimpleDateFormat">
<constructor-arg value="yyyy-MM-dd" />
</bean>
<bean id="employee" class="com.sfb.model.Employee">
<property name="ename" value="Javed"/>
<property name="dob">
<bean factory-bean="dateFormat" factory-method="parse">
<constructor-arg value="2010-09-30" />
</bean>
</property>
<property name="address" ref="address"/>
</bean>
<bean id="address" class="com.sfb.model.Address">
<property name="streetno" value="23"/>
<property name="city" value="Bhilai"/>
</bean>
</beans>
TestEmp.java:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.sfb.dao.EmployeeDao;
import com.sfb.model.Address;
import com.sfb.model.Employee;
public class TestEmp {
public static void main(String[] args) {
ApplicationContext context = new
ClassPathXmlApplicationContext("spring.xml");
EmployeeDao empDao= (EmployeeDao)context.getBean(EmployeeDao.class);
Employee emp = (Employee)context.getBean(Employee.class);
Address addr = (Address)context.getBean(Address.class);
empDao.save(emp,addr);
}
}
Address.java:
package com.sfb.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Address {
#Id
#GeneratedValue
#Column(name="street_no")
private int streetno;
#Column(name="city")
private String city;
public int getStreetno() {
return streetno;
}
public void setStreetno(int streetno) {
this.streetno = streetno;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
Employee.java:
package com.sfb.model;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity()
#Table(name="emp")
public class Employee {
#Column(name="e_name")
private String ename;
#Id
#GeneratedValue
#Column(name="e_id")
private int eid;
#Column(name="dob")
private Date dob;
#OneToOne(fetch = FetchType.LAZY, mappedBy = "address", cascade =
CascadeType.ALL)
private Address address;
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public int getEid() {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
EmployeeDao.java:
package com.sfb.dao;
import com.sfb.model.Address;
import com.sfb.model.Employee;
public interface EmployeeDao {
public void save(Employee emp , Address addr);
}
EmployeeDaoImpl.java
package com.sfb.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.sfb.dao.EmployeeDao;
import com.sfb.model.Address;
import com.sfb.model.Employee;
public class EmployeeDaoImpl implements EmployeeDao {
private SessionFactory sessionFactory;
#Override
public void save(Employee emp , Address addr) {
Session session = this.sessionFactory.openSession();
Transaction tx = session.beginTransaction();
emp.setAddress(addr);
session.persist(emp);
tx.commit();
session.close();
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
Exception StackTrace:
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.sfb.model.Employee
at org.hibernate.impl.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:548)
at org.hibernate.impl.SessionImpl.getEntityPersister(SessionImpl.java:1338)
at org.hibernate.engine.ForeignKeys.isTransient(ForeignKeys.java:180)
at org.hibernate.event.def.AbstractSaveEventListener.getEntityState(AbstractSaveEventListener.java:487)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:70)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:38)
at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:618)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:592)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:596)
at com.sfb.dao.EmployeeDaoImpl.save(EmployeeDaoImpl.java:20)
at com.sfb.mainemp.TestEmp.main(TestEmp.java:19)
Please help me thanks in advance
full StackTrace of NullpointerException:
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'AnnotatedSessionFactory' defined in class path resource [spring.xml]: Invocation of init method failed; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1403)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:545)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:871)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:423)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.sfb.mainemp.TestEmp.main(TestEmp.java:15)
Caused by: java.lang.NullPointerException
at org.hibernate.cfg.OneToOneSecondPass.doSecondPass(OneToOneSecondPass.java:135)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1127)
at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:296)
at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1112)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:717)
at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:188)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1460)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1400)
... 12 more
Here is an error (Employee.java):
#OneToOne(fetch = FetchType.LAZY, mappedBy = "address", cascade =
CascadeType.ALL)
private Address address;
mappedBy attribute should only used for inverse size of association, so it is not applicable here.
I guess you are trying to build simple unidirectional association.
It should look something like:
#OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name="ADDRESS_ID") /* this is the name of address id column in 'emp' table*/
private Address address;
Here is almost identical example from book.
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