0

I am unable to inject my DAO class in Spring MVC: This is my DAO class:

package com.pankaj.bookslibrary.dao;

@Component
public class BooksLibraryDAO 
{
    @PersistenceContext
    private EntityManager em;

    public void saveBook(Book book)
    {
        em.persist(book);
    }
}

This is my BO class which calls DAO:

package com.pankaj.bookslibrary.controller;

@Service
public class BooksLibraryBO 
{
    @Autowired
    private BooksLibraryDAO booksLibraryDAO; 

    public void saveBook(Book book)
    {
        booksLibraryDAO.saveBook(book);
    }

The above line gives NullPointerException as booksLibraryDAO is null. Here are the relevant lines from my dispatcherServlet config file:

<beans xmlns=...3.0.xsd">

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

    <bean id="dataSource"....</bean>

    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" />
        <property name="persistenceUnitName" value="BooksLibrary_PersistenceUnit" />
        <property name="dataSource" ref="dataSource" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="databasePlatform" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
                <property name="showSql" value="false" />
                <property name="generateDdl" value="true" />
            </bean>
        </property>
    </bean>


    <bean id="transactionManagerNonJTA" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
        <property name="defaultTimeout" value="1800"></property>
    </bean>
    <tx:annotation-driven transaction-manager="transactionManagerNonJTA" />

I am not sure what I have missed. This is how I am making a call from the controller:

BooksLibraryBO bo = new BooksLibraryBO();
bo.saveBook(book);
Pankaj Vaidya
  • 443
  • 3
  • 8

1 Answers1

1
  1. The packages the classes are in differs from the package you scan for annotations. Add the packages to the list of base-packages to scan for!

  2. As M.Deinum explained, you are creating the BooksLibraryBO yourself, spring do not know that instances and will not process the annotations.

Grim
  • 1,938
  • 10
  • 56
  • 123