@Autowired 对象获取空值

发布于 2024-10-14 13:21:52 字数 5223 浏览 11 评论 0原文

尝试建立一个项目,但通过 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 时,运行此命令会出现 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>

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

提前致谢。

更新: ContactDAOImpl 类:

@Repository
public class ContactDAOImpl extends HibernateDaoSupport implements ContactDAO{

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

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

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;

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);
    }

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>

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>

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>

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?

Thanks in advance.

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);
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

歌枕肩 2024-10-21 13:21:52

为了使用 Spring 功能(自动装配、调用后构造方法或方面),您需要让 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" />

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.

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. 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" />
三生殊途 2024-10-21 13:21:52

您需要在测试类的顶部使用它:

@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,看看是否有帮助。

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; 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. Usually that's done in a set up method for your test. You'll have better luck if you actually create an ApplicationContext somewhere. Try reading the XML from your CLASSPATH in a setup method and see if that helps.

泛滥成性 2024-10-21 13:21:52

你需要在 Spring 配置中使用它才能使自动装配工作

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

You need this in your Spring configuration for autowiring to work

xmlns:context="http://www.springframework.org/schema/context" 
....
<context:annotation-config/>
飞烟轻若梦 2024-10-21 13:21:52

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

Add @Component/@Repository to the DAO/DAOImpl.

久伴你 2024-10-21 13:21:52

您正在 spring 上下文之外创建 POJO。

如果您确实希望能够“手动”实例化,可以通过在配置中添加 来解决此问题,然后注释 ContactDAOImpl代码> 和 @Configurable

you are creating the POJO outside of the spring context.

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

一个人的旅程 2024-10-21 13:21:52

您需要从 Spring 上下文中检索 ContactDAO 实例。您正在使用 new 关键字初始化自己。

请参阅下面的链接;

@Autowired 注释无法在 JUnit 类中注入 bean< /a>

或者如果不是单元测试

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

You need to retrieve the ContactDAO instance from Spring context. You are initing yourself with new keyword.

See the below link;

@Autowired annotation not able to inject bean in JUnit class

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文