简体   繁体   English

@Autowired对象获取空值

[英]@Autowired objects getting null value

Trying to set up a project but fail at Autowiring objects through Spring. 尝试建立项目,但无法通过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;

Running this gives me a NullPointerException when cd.addContact is invoked. 运行此程序会在调用cd.addContact时给我一个NullPointerException。 The ContactDaoImpl: 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);
    }

My servlet file: 我的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>

My hibernate.cfg.xml file: 我的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>

My web.xml file: 我的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>

I suppose the error is that the SessionFactory isn't getting initialized via @Autowired correctly, but why is that? 我认为错误是SessionFactory无法通过@Autowired正确初始化,但是为什么呢? Could it be a simple directory structure/filepath problem or is it something more complicated? 可能是简单的目录结构/文件路径问题,还是更复杂?

Thanks in advance. 提前致谢。

UPDATE: ContactDAOImpl class: 更新:ContactDAOImpl类:

@Repository
public class ContactDAOImpl extends HibernateDaoSupport implements ContactDAO{

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

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

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 . 为了使用Spring功能(自动装配,调用后构造方法或方面),您需要让Spring实例化实例,而不是使用new

For instance: 例如:

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 will scan the classes in the classes in the se.hsr.web package to for classes with Spring annotations. AnnotationConfigApplicationContext将扫描se.hsr.web包中的类中的类,以se.hsr.web具有Spring批注的类。 It requires Spring 3.0 to work. 它需要Spring 3.0才能工作。 Before that you should add the following line in your applicationContext.xml file: 在此之前,您应该在applicationContext.xml文件中添加以下行:

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

You need this at the top of your test class: 您需要在测试课程的顶部:

@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 {

I assumed JUnit4; 我假设使用JUnit4; my oversight. 我的疏忽。

You do need the context configuration tag in an application context somewhere, but I don't see anyplace in your code where you're actually opening an application context file and creating an ApplicationContext. 您确实需要在某个地方的应用程序上下文中使用上下文配置标记,但是在您的代码中实际上没有打开应用程序上下文文件并创建ApplicationContext的任何地方。 Usually that's done in a set up method for your test. 通常,这是通过测试的设置方法来完成的。 You'll have better luck if you actually create an ApplicationContext somewhere. 如果您确实在某个地方创建了ApplicationContext,那么运气会更好。 Try reading the XML from your CLASSPATH in a setup method and see if that helps. 尝试使用设置方法从CLASSPATH中读取XML,看看是否有帮助。

you are creating the POJO outside of the spring context. 您是在Spring上下文之外创建POJO的。

if you really want to be able to instanciate "manually", you can fix this, by adding <context:spring-configured /> to your configuration, and then annotating ContactDAOImpl with @Configurable 如果您真的想“手动”实例化,可以通过<context:spring-configured />添加<context:spring-configured />并用@Configurable注释ContactDAOImpl来解决此问题。

You need this in your Spring configuration for autowiring to work 您需要在Spring配置中使用此功能,以实现自动装配

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

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

You need to retrieve the ContactDAO instance from Spring context. 您需要从Spring上下文中检索ContactDAO实例。 You are initing yourself with new keyword. 您正在使用new关键字来初始化自己。

See the below link; 见下面的链接;

@Autowired annotation not able to inject bean in JUnit class @Autowired注释无法在JUnit类中注入bean

or if not unit test 或者如果不是单元测试

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 http://static.springsource.org/spring/docs/2.0.x/reference/beans.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM