2011-01-27 104 views
8

嘗試設置項目,但在通過Spring自動裝配對象時失敗。@Autowired objects null value

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時給我一個NullPointerException。 的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文件:

<?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文件:

<?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文件:

<?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> 

我想錯誤是th在SessionFactory沒有通過@Autowired正確初始化,但爲什麼呢?它可能是一個簡單的目錄結構/文件路徑問題還是更復雜的東西?

在此先感謝。

UPDATE: ContactDAOImpl類:

@Repository 
public class ContactDAOImpl extends HibernateDaoSupport implements ContactDAO{ 

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

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

的可能重複標註ContactDAOImpl [爲什麼我的春節@Autowired場空?(http://stackoverflow.com/questions/19896870/why-is-my-spring-autowired-field-null) – chrylis 2013-11-11 06:31:00

回答

14

爲了使用Spring特性(自動裝配,調用post構造方法或方面),你需要讓Spring實例化實例而不是使用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將掃描類的類在se.hsr.web包與Spring註解類。它需要Spring 3.0才能工作。在此之前,你應該加入下面一行在你applicationContext.xml文件:

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

需要檢索從Spring上下文中的ContactDAO實例。您正在使用new關鍵字啓動自己。

請參閱下面的鏈接;

@Autowired annotation not able to inject bean in JUnit class

,或者如果沒有單元測試

ClassPathResource resource = new ClassPathResource("beans.xml"); 
BeanFactory factory = new XmlBeanFactory(resource); 
beanFactory.getBean("nameOfYourBean"); 

http://static.springsource.org/spring/docs/2.0.x/reference/beans.html

+0

你能解釋一下你怎麼個意思,我應該做的一點點?我嘗試將testrunner中的ContactDAO替換爲@Autowired ContactDAO contactDAO;但它也給了我一個NullPointerException。 – 2011-01-27 12:36:31

+0

剛剛看到鏈接,會閱讀它非常感謝。 – 2011-01-27 12:37:07

2

你需要在這個測試類的頂部:

@RunWith(SpringJUnit4ClassRunner.class) 
// ApplicationContext will be loaded from "/applicationContext.xml" and "/applicationContext-test.xml" 
// in the root of the classpath 
@ContextConfiguration(locations={"/applicationContext.xml", "/applicationContext-test.xml"}) 
public class MyTest { 

我假定JUnit4;我的疏忽。

您確實需要某處應用程序上下文中的上下文配置標記,但在代碼中您沒有看到實際打開應用程序上下文文件並創建ApplicationContext的任何位置。通常,這是通過您的測試設置方法完成的。如果你實際創建了一個ApplicationContext,你會有更好的運氣。嘗試從安裝方法中讀取CLASSPATH中的XML並查看是否有幫助。

+0

對不起,我的課是誤導性的,它不是一個真正的測試類,只是一個名爲TestRunner的類,我創建了這個類來試用這個功能。 @ContextConfiguration的東西是否適用? – 2011-01-27 12:41:49

+0

不,您需要根據Michael Borgwart的回答在context.xml中的。 – sourcedelica 2011-01-27 13:22:58

1

你在你的Spring配置需要這個自動裝配工作

xmlns:context="http://www.springframework.org/schema/context" 
.... 
<context:annotation-config/> 
1

添加@Component/@Repository到DAO/DAOImpl。

1

您正在春季環境之外創建POJO。

如果你真的希望能夠實例化「手動」,就可以解決這個問題,通過增加<context:spring-configured />到您的配置,然後用@Configurable