@Autowired对象获取空值 [英] @Autowired objects getting null value

查看:161
本文介绍了@Autowired对象获取空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试设置项目但在通过Spring自动装配对象时失败。

Trying to set up a project but fail at Autowiring objects through Spring.

package se.hsr.web;

public class TestRunner {

    public static void main(String[] args) {
        ContactDAO cd = new ContactDAOImpl();
        Contact contact = new Contact();
        contact.setFirstname("Zorro");
        cd.addContact(contact);
    }

}

package se.hsr.web;

当调用cd.addContact时,运行this会给我一个NullPointerException。
ContactDaoImpl:

Running this gives me a NullPointerException when cd.addContact is invoked. The ContactDaoImpl:

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class ContactDAOImpl implements ContactDAO {

    @Autowired
    private SessionFactory sessionFactory;

    public void addContact(Contact contact) {
        sessionFactory.getCurrentSession().save(contact);
    }

我的servlet文件:

My servlet file:

    <?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:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan
        base-package="se.hsr.web"/>

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
        p:location="/WEB-INF/jdbc.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}" />  

     <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${jdbc.dialect}</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <bean id="contactDAOImpl"
        class="se.hsr.web.ContactDAOImpl"/>

    <context:annotation-config/>

</beans>

我的hibernate.cfg.xml文件:

My hibernate.cfg.xml file:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <mapping class="se.hsr.web.Contact" />
    </session-factory>

</hibernate-configuration>

我的web.xml文件:

My web.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>HSRMVC</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <servlet>
        <servlet-name>HSR</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>HSR</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

我认为错误是SessionFactory没有通过@Autowired正确初始化,但为什么是那?它可能是一个简单的目录结构/文件路径问题还是更复杂的东西?

I suppose the error is that the SessionFactory isn't getting initialized via @Autowired correctly, but why is that? Could it be a simple directory structure/filepath problem or is it something more complicated?

提前致谢。

更新:
ContactDAOImpl类:

UPDATE: ContactDAOImpl class:

@Repository
public class ContactDAOImpl extends HibernateDaoSupport implements ContactDAO{

    @Autowired
    @Qualifier("sessionFactory")
    private SessionFactory sessionFactory;

    public void addContact(Contact contact) {
        sessionFactory.getCurrentSession().save(contact);
    }


推荐答案

为了使用Spring功能(自动装配,调用post构造方法或方面)你需要让Spring实例化实例而不是使用 new

In order to use Spring features (autowiring, call to post construct methods or aspects) you need to let Spring instanciate the instances instead of using new.

例如:

public static void main(String[] args) {
    ApplicationContext context = AnnotationConfigApplicationContext("se.hsr.web")
    ContactDAO cd = (ContactDAO)context.getBean("contactDAOImpl");
    Contact contact = new Contact();
    contact.setFirstname("Zorro");
    cd.addContact(contact);
}

AnnotationConfigApplicationContext 将扫描对于带有Spring注释的类, se.hsr.web 包中的类中的类。它需要Spring 3.0才能工作。在此之前,您应该在 applicationContext.xml 文件中添加以下行:

AnnotationConfigApplicationContext will scan the classes in the classes in the se.hsr.web package to for classes with Spring annotations. It requires Spring 3.0 to work. Before that you should add the following line in your applicationContext.xml file:

<context:component-scan base-package="se.hsr.web" />

这篇关于@Autowired对象获取空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆