Spring3 - Autowired没有发生。该对象为null

时间:2014-08-14 14:09:36

标签: java spring spring-mvc autowired

servlet.xml中

我正在使用注释而不是在XML中创建bean。

我添加了" context:annotation-config"在我的XML中

<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" 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/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
    <context:component-scan base-package="com.hemanths.expense.manager"/>
    <mvc:annotation-driven/>
    <tx:annotation-driven/>
    <context:annotation-config />

    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="configLocation" value="WEB-INF/hibernate.cfg.xml"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

</beans>

UserDaoImpl.java

package com.hemanths.expense.manager.hibernate.dao.impl;

import com.hemanths.expense.manager.hibernate.dao.UserDao;
import com.hemanths.expense.manager.hibernate.entity.User;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class UserDaoImpl implements UserDao {
    @Autowired
    private SessionFactory sessionFactory;

    public UserDaoImpl() {
    }

    public UserDaoImpl(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Override
    public void addUser(User user) {
        sessionFactory.getCurrentSession().save(user);
    }
}

UserService.java

package com.hemanths.expense.manager.service.impl;

import com.hemanths.expense.manager.hibernate.dao.UserDao;
import com.hemanths.expense.manager.hibernate.entity.User;
import com.hemanths.expense.manager.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    public UserServiceImpl() {
    }

    public UserServiceImpl(UserDao userDao){
        this.userDao = userDao;
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    @Transactional
    public void addUser(User user) {
        userDao.addUser(user);
    }

UserServiceImplTest.java

public class UserServiceImplTest {

    @Autowired
    UserService userService;

    @Test
    public void shouldAddUser() {
        User user = new User("firstName", "lastName", new Date(), "M", "username", "password");
        userService.addUser(user);
    }
}

堆栈跟踪

java.lang.NullPointerException
    at com.hemanths.expense.manager.service.impl.UserServiceImplTest.shouldAddUser(UserServiceImplTest.java:18)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:74)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:211)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:67)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

目录结构

enter image description here

3 个答案:

答案 0 :(得分:1)

我得到了答案。谢谢@Andrei Stefan。

因为我正在运行测试,所以我必须使用您的xml文件路径注释如下所示的测试。

@ContextConfiguration(locations = {"classpath:mvc-dispatcher-servlet.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class UserServiceImplTest {

@Autowired
UserService userService;

@Test
public void shouldAddUser() {
    User user = new User("firstName", "lastName", new Date(), "M", "username", "password");
    userService.addUser(user);
}
}

答案 1 :(得分:0)

你的休眠的示例用法;

<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" 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/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

<context:component-scan base-package="com.base.package"/>
<mvc:annotation-driven/>
<tx:annotation-driven/>
<context:annotation-config />

<bean id="_hibernateSessionFactory"
      class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="configLocation" value="WEB-INF/hibernate.cfg.xml"/>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.show_sql">true</prop>
        </props>
    </property>
</bean>

 <!-- userDao Repo -->
    <bean id="_userDao"
        class="com.hemanths.expense.manager.hibernate.dao.impl.UserDaoImpl">
        <property name="_hibernateSessionFactory">
            <ref bean="_hibernateSessionFactory"></ref>
        </property>
    </bean>


 <!-- userService Repo -->
    <bean id="_userDao"
        class="com.hemanths.expense.manager.service.impl.UserServiceImpl">
        <property name="_hibernateSessionFactory">
            <ref bean="_hibernateSessionFactory"></ref>
        </property>
    </bean>

</beans>

使用getter和setter在DaoImpl中添加hibernate类:

private SessionFactory _hibernateSessionFactory;

在你想要的控制器中使用autowire:

@Autowired
private UserServiceImpl _userServiceImpl;

答案 2 :(得分:0)

正如评论中所提到的,您不需要在servlet.xml文件中为您的服务和DAO类创建bean:

<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" 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/context     http://www.springframework.org/schema/context/spring-context.xsd     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

<context:component-scan base-package="com.hemanths.expense.manager"/>
<mvc:annotation-driven/>
<tx:annotation-driven/>
<context:annotation-config />

<bean id="sessionFactory"
  class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="configLocation" value="WEB-INF/hibernate.cfg.xml"/>
<property name="hibernateProperties">
    <props>
        <prop key="hibernate.show_sql">true</prop>
    </props>
</property>
</bean>

</beans>

您也不需要为服务和DAO类提供构造函数,因为它们是Spring组件:

@Repository("userDao")
public class UserDaoImpl implements UserDao {

    @Autowired
    private SessionFactory sessionFactory;

    // Methods here

}


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    // Methods here

}