Saswati
Saswati

Reputation: 1

How to resolve BeanCreationException?

Working on Spring 4 CRUD application and the application is completely annotation based and no XML configuration is used.

Below is the stack tarce of the exception:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.springrest.annotationbased.crudexampleapplication.service.EmployeeService com.springrest.annotationbased.crudexampleapplication.controller.EmployeeController.employeeService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.springrest.annotationbased.crudexampleapplication.dao.EmployeeDao com.springrest.annotationbased.crudexampleapplication.service.EmployeeServiceImpl.employeeDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeDao': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.springrest.annotationbased.crudexampleapplication.dao.EmployeeDaoImpl.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class com.springrest.annotationbased.crudexampleapplication.configuration.HibernateConfiguration: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.orm.hibernate4.LocalSessionFactoryBean com.springrest.annotationbased.crudexampleapplication.configuration.HibernateConfiguration.sessionFactory()] threw exception; nested exception is java.lang.NullPointerException
            at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
            at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
            at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
            at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
            at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
            at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
            at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
            at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
            at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
            at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
            at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
            at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
            at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
            at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
            at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4851)
            at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5314)
            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:1142)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
            at java.lang.Thread.run(Thread.java:745)

Below are the java files

HibernateConfiguration.java

package com.springrest.annotationbased.crudexampleapplication.configuration;

         @Configuration
         @EnableTransactionManagement
         @ComponentScan({ "com.springrest.annotationbased.crudexampleapplication" })
         @PropertySource(value = "classpath:application.properties")
         public class HibernateConfiguration {
          @Autowired
          private Environment env;
          @Bean
         public LocalSessionFactoryBean sessionFactory() {
         LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
         Properties props = new Properties();
         // Setting JDBC properties
         props.put("mysql.driver", env.getProperty("mysql.driver"));
         props.put("mysql.url", env.getProperty("mysql.url"));
        props.put("mysql.user", env.getProperty("mysql.user"));
        props.put("mysql.password", env.getProperty("mysql.password"));
        // Setting Hibernate properties
        props.put("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
        props.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
        props.put("hibernate.dialect", env.getProperty("org.hibernate.dialect.MySQLDialect"));
        sessionFactory.setPackagesToScan(new String[] { "com.springrest.annotationbased.crudexampleapplication.model" });
        sessionFactory.setHibernateProperties(props);
        return sessionFactory;
        }
        @Bean
        @Autowired
        public HibernateTransactionManager transactionManager(SessionFactory s) {
        HibernateTransactionManager txManager = new HibernateTransactionManager();
         txManager.setSessionFactory(s);
        return txManager;

 }}

MyWebAppInitializer.java

  package com.springrest.annotationbased.crudexampleapplication.configuration;

public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {



 @Override
    protected Class<?>[] getRootConfigClasses() {
       // TODO Auto-generated method stub
       return new Class[] { HibernateConfiguration.class };
     }

     @Override
    protected Class<?>[] getServletConfigClasses() {
       // TODO Auto-generated method stub
     return new Class[] { WebConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
    // TODO Auto-generated method stub

    return new String[] { "/" };
  }
}

WebConfig.java

     package com.springrest.annotationbased.crudexampleapplication.configuration;

 @Configuration
 @EnableWebMvc
@ComponentScan(basePackages="com.springrest.annotationbased.crudexampleapplication")
 public class WebConfig extends WebMvcConfigurerAdapter {



}

EmployeeController.java

@RestController

public class EmployeeController {

 @Autowired
EmployeeService employeeService;

//logic goes here  

    }

EmployeeServiceImpl

  @Service("employeeService")
     @Transactional

    public class EmployeeServiceImpl implements EmployeeService {

      @Autowired
       private EmployeeDao employeeDao;

      // business logic  

}

EmployeeDaoImpl.java

 @Repository("employeeDao")
 public class EmployeeDaoImpl implements EmployeeDao {

@Autowired
 private SessionFactory sessionFactory;

 // persistence logic  

     }

EmployeeEntity.java

 @Entity
 @Table(name="employee")
 public class EmployeeEntity implements Serializable{

 private static final long serialVersionUID = 1L;

 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 @Column(name="empid")
 private Integer employeeId;

 @Column(name="empname")
 private String employeeName;

 @Column(name="empAddress")
 private String employeeAddress;

@Column(name="salary")
private Long salary;

@Column(name="empAge")
private Integer employeeAge;

        // getters and setters

}

Application.properties

mysql.driver = com.mysql.jdbc.Driver
mysql.url = jdbc:mysql://localhost:3306/mydatabase
mysql.user = root
mysql.password = root

#Hibernate properties
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.hbm2ddl.auto = update

#C3P0 properties
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.acquire_increment=1
hibernate.c3p0.timeout=1800
hibernate.c3p0.max_statements=150

Upvotes: 0

Views: 3795

Answers (1)

sam
sam

Reputation: 25

In HibernateConfiguration.java you have given your own set of variables as key in put method.This is wrong,you have to mention it as

// Setting JDBC properties
        props.put(DRIVER, env.getProperty("mysql.driver"));
        props.put(URL, env.getProperty("mysql.jdbcUrl"));
        props.put(USER, env.getProperty("mysql.username"));
        props.put(PASS, env.getProperty("mysql.password"));

    // Setting Hibernate properties
    props.put(SHOW_SQL, env.getProperty("hibernate.show_sql"));
    props.put(HBM2DDL_AUTO, env.getProperty("hibernate.hbm2ddl.auto"));
    props.put(DIALECT, env.getProperty("hibernate.dialect"));

here, DRIVER,URL,USER etc are static variables and make sure that you have imported the following package,

import static org.hibernate.cfg.Environment.*;

Upvotes: 1

Related Questions