自动装配似乎失败了

时间:2014-12-23 22:27:05

标签: java spring autowired

我知道这个问题被多次询问,但我现在看了几个晚上,我似乎无法找出为什么Autowired字段保持为空。我盯着它看,所以也许你们中的某些人看到了什么是错的。

我有以下代码:

ApplicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd ">
    <context:component-scan base-package="com.skoerkamp"/>
    <import resource="ApplicationContext-persistence.xml"/>
    </beans>

的ApplicationContext-的persistence.xml

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
    <tx:annotation-driven transaction-manager="transactionManager"/>
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="packagesToScan" value="com.skoerkamp.model"/>
        <property name="dataSource" ref="dataSource"/>
        <property name="persistenceUnitName" value="GP_UNIT"/>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
                <!--
                <prop key="hibernate.hbm2ddl.auto">create-drop</prop>
                -->
            </props>
        </property>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="false"/>
                <property name="generateDdl" value="false"/>
            </bean>
        </property>
    </bean>
    <!-- DB configuration  -->
    <bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="<connection-url>"/>
        <property name="username" value="<user>"/>
        <property name="password" value="<pw>"/>
    </bean>

</beans>

的pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.skoerkamp</groupId>
    <artifactId>groupplanner</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>Group Planner Server</name>
    <url>http://maven.apache.org</url>

    <repositories>
        <repository>
            <id>maven2-repository.java.net</id>
            <name>Java.net Repository for Maven</name>
            <url>http://download.java.net/maven/2/</url>
            <layout>default</layout>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-server</artifactId>
            <version>1.8</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20141113</version>
        </dependency>
        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>jsr311-api</artifactId>
            <version>1.1.1</version>
        </dependency>

        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.1.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.1.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.1.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.1.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.1.3.RELEASE</version>
        </dependency>

        <!--Database-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.24</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.1.3.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.3.7.Final</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>groupplanner</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.mortbay.jetty</groupId>
                <artifactId>maven-jetty-plugin</artifactId>
                <version>6.1.16</version>
                <configuration>
                    <scanIntervalSeconds>10</scanIntervalSeconds>
                    <stopPort>8005</stopPort>
                    <stopKey>STOP</stopKey>
                    <webApp>
                        <contextPath>/groupplanner</contextPath>
                    </webApp>
                </configuration>
                <executions>
                    <execution>
                        <id>start-jetty</id>
                        <phase>pre-integration-test</phase>
                        <goals>
                            <goal>run</goal>
                        </goals>
                        <configuration>
                            <scanIntervalSeconds>0</scanIntervalSeconds>
                            <daemon>true</daemon>
                        </configuration>
                    </execution>
                    <execution>
                        <id>stop-jetty</id>
                        <phase>post-integration-test</phase>
                        <goals>
                            <goal>stop</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

仅出于测试目的,只需拨打我的服务即可。

package com.skoerkamp.rest;

import com.skoerkamp.service.CalendarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.ws.rs.GET;
import javax.ws.rs.Path;

@Path("/calendar")
@Service
public class CalendarEndpoint {

    @Autowired
    private CalendarService calendarService;

    @GET
    public String getCalendarItems() {
        calendarService.create();
        return "";
    }

}

服务:

package com.skoerkamp.service;

import com.skoerkamp.model.CalendarItem;
import com.skoerkamp.repository.CalendarRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Service
public class CalendarService {

    @Autowired
    private CalendarRepository calendarRepository;

    public void create() {
        calendarRepository.create(new CalendarItem("TEST"));
    }
}

这是我得到的堆栈跟踪的一部分:

java.lang.NullPointerException
    at com.skoerkamp.rest.CalendarEndpoint.getCalendarItems(CalendarEndpoint.java:23)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
    at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatch

第23行是对calendarService的调用。

抱歉长篇文章,但我想尽可能清楚地表明我的问题。任何意见或建议表示赞赏!在此先感谢:)

3 个答案:

答案 0 :(得分:1)

使用Spring,Autowire将始终连接bean,否则它将失败,除非您特别将其标记为@autowired(required = false)如果您获得空指针并且它不是自动装配,则意味着您没有使用Spring来管理您的豆子。

您需要使用Spring MVC(Spring DispatcherServlet)来实例化您的对象。看看http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html中的17.2。这将向您展示如何配置项目(使用XML或仅使用Annotation),以便Spring管理您的bean并正确地自动装配所有内容。

答案 1 :(得分:0)

为了加载bean并自动装配它们,您需要在web.xml中配置ContextLoaderListener并指定主要上下文的位置,例如“ApplicationContext.xml”,默认情况下为ContextLoaderListener加载以下文件上下文“/WEB-INF/applicationContext.xml”,因此请相应地重命名文件。以下是一些可以帮助您设置和理解上下文加载器机制的链接:

http://www.springbyexample.org/examples/simple-spring-mvc-form-annotation-config-webapp.html#simple-spring-mvc-form-annotation-config-webapp-web-config http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#context-create

以及解释如何使用Spring 3逐步创建restful api的教程:http://www.ibm.com/developerworks/web/library/wa-spring3webserv/index.html?ca=drs-

答案 2 :(得分:0)

你需要在界面而不是类上使用@Autowired注释。

所以,创建一个接口,让CalendarService类实现它,然后自动装配接口。

希望它有效!