Getting Error of Error creating bean with name 'bookMasterController': Injection of autowired dependencies failed;

3.4k Views Asked by At

I am using Spring 3.2 and Hibernate but i am getting eror of that its not allowing to create bean of SessionFacotry from the XML file i dont know why this error is coming. i have search alot but not finding exceat ans please help for the same.

Here my file is XML

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

    <!-- For context suppport of the Controller -->

    <context:annotation-config></context:annotation-config>
    <context:component-scan base-package="com.book.controller"></context:component-scan>


    <!-- For enable the MVC Support -->
    <!-- <mvc:annotation-driven />
    <mvc:resources mapping="/resources/**" location="/WEB-INF/resources/"></mvc:resources>
 -->
    <!-- Enabling the suppot the UI user side -->
    <bean id="jspViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
    </bean>




    <!-- For messages for the Labels -->

    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>


    <!-- For the Properties of JDBC -->
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
        p:location="/WEB-INF/jdbc.properties" />

    <!--Database Properties -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
        p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}" />

    <!-- Session facotry configration -->
    <bean id="hibernate4AnnotatedSessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property> -->
        <property name="packagesToScan" value="com.book.bookentity" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${jdbc.dialect}</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <!-- implementation bean config. -->

    <bean id="autherMasterServiceInterfacecontroller" class="com.book.service.AutherMasterServiceInterfaceImpl"></bean>
    <bean id="bookMasterServiceInterfacecontroller" class="com.book.service.BookMasterServiceInterfaceImpl"></bean>
    <bean id="emailMasterInterfacecontroller" class="com.book.service.EmailMasterInterfaceImpl"></bean>
    <bean id="languageMasterinterfacecontroller" class="com.book.service.LanguageMasterinterfaceimpl"></bean>




    <bean id="bookMasterInterface" class="com.book.bookDao.BookMasterInterfaceImpl">
        <property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
    </bean>
    <bean id="emailMasterInterface" class="com.book.bookDao.EmailMasterInterfaceImpl">
        <property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
    </bean>
    <bean id="languageMasterInterface" class="com.book.bookDao.LanguageMasterInterfaceImpl">
        <property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
    </bean>
    <bean id="autherMasterInterface" class="com.book.bookDao.AutherMasterInterfaceImpl">
        <property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
    </bean>



    <!-- Enabling transction managar -->
    <tx:annotation-driven transaction-manager="transactionManager" />


    <!-- Config Tranaction Managar -->
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
    </bean>


</beans>

bean class1

@Entity
@Table(name = "tbl_bookmaster", uniqueConstraints = { @UniqueConstraint(columnNames = "bid") })
public class BookMasterTable {

    @Id
    @GeneratedValue
    @Column(name = "bid")
    private int bookid;

    @Column(name = "bookname")
    private String bookname;

    @Column(name = "booktype")
    private String booktype;

    @Column(name = "bookprice")
    private String bookprice;

    @Column(name = "bestsaler")
    private int bestsaller;

    @ManyToOne
    @JoinColumn(name = "lid")
    private LanguageMasterTable languageMasterTable;

    @ManyToOne
    @JoinColumn(name = "auid")
    private AutherMasterTable autherMasterTable;

    @ManyToOne
    @JoinColumn(name = "mailid")
    private EmailMasterTable emailMasterTable;


    // getter and setter

    }

bean2

@Entity
@Table(name = "tbl_contactmaster")
public class EmailMasterTable implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    @OneToMany
    @JoinColumn(name = "authercontactmail")
    private Set<BookMasterTable> bookMasterTables;

    @Column(name = "emailcontact")
    private String emailcontact;

}

bean 3

@Entity
@Table(name = "tbl_authermaster")
public class AutherMasterTable {

    @Id
    @GeneratedValue
    @OneToMany
    @JoinColumn(name = "auid")
    private Set<BookMasterTable> bookMasterTables;

    @Column(name = "authername")
    private String authername;
   // getter and setter
}

bean 4

public class LanguageMasterTable {

    @Id
    @GeneratedValue
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name = "language")
    private Set<BookMasterTable> bookMasterTables;

    @Column(name = "languagename")
    private String languagename;

    // getter and setter
}

controller bean

@Controller
public class BookMasterController {

    @Autowired
    private BookMasterServiceInterface bookMasterServiceInterfacecontroller;


    @RequestMapping(value="/addbook",method= RequestMethod.POST)
    public String addAuther(@ModelAttribute("book") BookMasterTable bookMasterTable){

        bookMasterServiceInterfacecontroller.addBook(bookMasterTable);
        return "bookadded";
    }
}

like that having all controller for each bean class

service interface

public interface BookMasterServiceInterface {
    public void addBook(BookMasterTable bookMasterTable);
}

service calss

@Service
public class BookMasterServiceInterfaceImpl implements BookMasterServiceInterface{
    @Autowired
    private BookMasterInterface bookMasterInterface;

    @Override
    @Transactional
    public void addBook(BookMasterTable bookMasterTable) {
        // TODO Auto-generated method stub
        bookMasterInterface.addBooks(bookMasterTable);

    }
}

like that having service for all bean

Repository class interface

public interface BookMasterInterface {
    public void addBooks(BookMasterTable bookMasterTable);
}

repository class implementation having for each bean

@Repository
public class BookMasterInterfaceImpl implements BookMasterInterface {
    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public void addBooks(BookMasterTable bookMasterTable) {
        // TODO Auto-generated method stub

        try {
            sessionFactory.getCurrentSession().save(bookMasterTable);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

}

and what error i am getting is.

Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.book.service.BookMasterServiceInterface com.book.controller.BookMasterController.bookMasterServiceInterfacecontroller; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'bookMasterServiceInterfacecontroller': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.book.bookDao.BookMasterInterface com.book.service.BookMasterServiceInterfaceImpl.bookMasterInterface; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'bookMasterInterface': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.book.bookDao.BookMasterInterfaceImpl.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/BookServletmvc-servlet.xml]: Invocation of init method failed; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:517)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:286)
    ... 20 more

main this is that is not allowing to create because its getting null pointer but i dont know where here.

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/BookServletmvc-servlet.xml]: Invocation of init method failed; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1512)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:912)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:855)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:770)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:489)
    ... 48 more
Caused by: java.lang.NullPointerException
    at org.hibernate.cfg.Ejb3JoinColumn.checkReferencedColumnsType(Ejb3JoinColumn.java:538)
    at org.hibernate.cfg.BinderHelper.createSyntheticPropertyReference(BinderHelper.java:126)
    at org.hibernate.cfg.ToOneFkSecondPass.doSecondPass(ToOneFkSecondPass.java:116)
    at org.hibernate.cfg.Configuration.processEndOfQueue(Configuration.java:1514)
    at org.hibernate.cfg.Configuration.processFkSecondPassInOrder(Configuration.java:1437)
    at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1355)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1724)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1775)
    at org.springframework.orm.hibernate4.LocalSessionFactoryBuilder.buildSessionFactory(LocalSessionFactoryBuilder.java:247)
    at org.springframework.orm.hibernate4.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:373)
    at org.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:358)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1571)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1509)
    ... 58 more

i will be happy if u can help :)

i have four entities. first one is

@Entity
@Table(name = "tbl_bookmaster", uniqueConstraints = { @UniqueConstraint(columnNames = "bid") })
public class BookMasterTable {

    @Id
    @GeneratedValue
    @Column(name = "bid")
    private int bookid;

    @Column(name = "bookname")
    private String bookname;

    @Column(name = "booktype")
    private String booktype;

    @Column(name = "bookprice")
    private String bookprice;

    @Column(name = "bestsaler")
    private int bestsaller;

    @ManyToOne
    @JoinColumn(name = "lid")
    private LanguageMasterTable languageMasterTable;

    @ManyToOne
    @JoinColumn(name = "auid")
    private AutherMasterTable autherMasterTable;

    @ManyToOne
    @JoinColumn(name = "mailid")
    private EmailMasterTable emailMasterTable;

    public int getBookid() {
        return bookid;
    }

    public void setBookid(int bookid) {
        this.bookid = bookid;
    }

    public String getBookname() {
        return bookname;
    }

    public void setBookname(String bookname) {
        this.bookname = bookname;
    }

    public String getBooktype() {
        return booktype;
    }

    public void setBooktype(String booktype) {
        this.booktype = booktype;
    }

    public String getBookprice() {
        return bookprice;
    }

    public void setBookprice(String bookprice) {
        this.bookprice = bookprice;
    }

    public int getBestsaller() {
        return bestsaller;
    }

    public void setBestsaller(int bestsaller) {
        this.bestsaller = bestsaller;
    }

    public LanguageMasterTable getLanguageMasterTable() {
        return languageMasterTable;
    }

    public void setLanguageMasterTable(LanguageMasterTable languageMasterTable) {
        this.languageMasterTable = languageMasterTable;
    }

    public AutherMasterTable getAutherMasterTable() {
        return autherMasterTable;
    }

    public void setAutherMasterTable(AutherMasterTable autherMasterTable) {
        this.autherMasterTable = autherMasterTable;
    }

    public EmailMasterTable getEmailMasterTable() {
        return emailMasterTable;
    }

    public void setEmailMasterTable(EmailMasterTable emailMasterTable) {
        this.emailMasterTable = emailMasterTable;
    }

}
2

There are 2 best solutions below

1
On BEST ANSWER

I think the problem is here, in AutherMasterTable (and similar places in other entities):

@Id
@GeneratedValue
@OneToMany
@JoinColumn(name = "auid")
private Set<BookMasterTable> bookMasterTables;

For a one-to-many join, the join column mentioned in the JoinColumn annotation is in the other table. It does not refer to a column in this table. Besides, a Set cannot be an identifier.

Try using two fields instead:

@Id
@GeneratedValue
@Column(name = "auid")
private int autherId;

@OneToMany
@JoinColumn(name = "auid")
private Set<BookMasterTable> bookMasterTables;

Note that we are not defining the same column twice in the same table: the first mention of auid above refers to a column in tbl_authermaster and the second one refers to the auid column in tbl_bookmaster.

Despite your mistake, Hibernate should not be throwing a NullPointerException at you. That is a bug in Hibernate.

0
On

Reading the stacktrace, you know where:

java.lang.NullPointerException
    at org.hibernate.cfg.Ejb3JoinColumn.checkReferencedColumnsType(Ejb3JoinColumn.java:538)
    at ...

You should run in debug with a breakpoint at that line, but I'd think that basically means you have an error in your entity, your mapping or on the database it's run on. If you can, you should generate the schema with Hibernate, then you should compare the difference between your target schema and the generated schema => that would print the mapping error.

Also there are no mappedBy on your OneToMany and ManyToOne. You should check that first (it is not an error to not have them, but it might become a problem if the database schema is not in sync with Hibernate expected schema).