无法在Spring BO中注入DAO类

时间:2016-02-02 05:36:00

标签: java spring jpa dependency-injection

我无法在Spring MVC中注入我的DAO类: 这是我的DAO课程:

package com.pankaj.bookslibrary.dao;

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

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

这是我的BO类,它调用DAO:

package com.pankaj.bookslibrary.controller;

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

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

上面的行给出了NullPointerException,因为booksLibraryDAO为null。 以下是我的dispatcherServlet配置文件中的相关行:

<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" />

我不确定我错过了什么。 这就是我从控制器拨打电话的方式:

BooksLibraryBO bo = new BooksLibraryBO();
bo.saveBook(book);

1 个答案:

答案 0 :(得分:1)

  1. 类所包含的包与您扫描注释的包不同。将包添加到base-packages列表中以进行扫描!

  2. 正如M.Deinum解释的那样,你自己正在创建BooksLibraryBO,春天不知道那些实例,也不会处理注释。