对于Web项目,Autowired Object将为null

时间:2014-11-24 09:13:49

标签: spring

我总是将autowired对象null,请帮忙。从日志bean中正确初始化。

=============================================== ==================================== 的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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>RestfulService</display-name>
  <!-- <welcome-file-list>
    <welcome-file>Readme.html</welcome-file>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list> -->

  <servlet>
    <servlet-name>Jersey REST Service</servlet-name>

   <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> 
    <init-param>
      <param-name>jersey.config.server.provider.packages</param-name>
      <param-value>com.restfulservice.gateway</param-value>
    </init-param>

    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/api/*</url-pattern>
  </servlet-mapping>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

    <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/ApplicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

</web-app>

=============================================== =========================================== 的applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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">


 <!-- <bean 
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> -->

    <context:component-scan base-package="com.restfulservice" />
    <context:annotation-config/>
    <!-- <context:property-placeholder location="classpath:testme.properties" /> -->

     <bean id="incomingCall" class="com.restfulservice.gateway.IncomingCall" />

    <bean id="testPropertyRead1" class="com.restfulservice.gateway.TestPropertyRead">
    <property name="name" value="${name}"/>    
    <property name="address" value="${address}"/>



</beans>

=============================================== ============================================ incomingcall.java

package com.restfulservice.gateway;
import java.io.File;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

//@Path("/v1/status/*")
@Path("/v1status")
@Component

public class IncomingCall {

    final static Logger logger = Logger.getLogger(IncomingCall.class);

    public static final String Version = "0.0.1";

    @Autowired  
    @Qualifier("testPropertyRead1")
    private TestPropertyRead testPropertyRead;

    public TestPropertyRead getTestPropertyRead() {
        return testPropertyRead;
    }


    public void setTestPropertyRead(TestPropertyRead testPropertyRead) {
        this.testPropertyRead = testPropertyRead;
    }


    @GET
    @Produces(MediaType.TEXT_HTML)
    public String returnTitle()
    {
        logger.debug("inside returnTitle function call");
        return "<p> Java Rest Web Service JSB ....</p>";
    }


    @Path("/version")
    @GET
    @Produces(MediaType.TEXT_HTML)
    public String returnVersion()
    {
        return "<p> Java Rest Web Service JSB ....</p>" + "Version:" + Version;
    }

    @Path("/testspring")
    @GET
    @Produces(MediaType.TEXT_HTML)
    public String testSpring()
    {
        logger.debug("inside testSpring function call");

        logger.info("sai baba is awesome he is making me work, he is my energy");

        ApplicationContext context = new ClassPathXmlApplicationContext(
                "SpringBeans.xml");

        TestSpringSimple obj = (TestSpringSimple) context.getBean("testsprings1");
        obj.printHello();
        logger.info("going to call callhibernate");
        obj.callHibernate();
        logger.info("called callhibernate");
        return "<p> Java Rest Web Service JSB ...testing spring</p>";       
    }

    @Path("/testconfigreader")
    @GET
    @Produces(MediaType.TEXT_HTML)
    public String testConfigReader()
    {
        logger.debug("inside testConfigReader function call");



        /*ApplicationContext context = new ClassPathXmlApplicationContext(
                "ApplicationContext.xml");

        TestPropertyRead obj = (TestPropertyRead) context.getBean("testconfig");
*/      

        //TestPropertyRead testconfig = (TestPropertyRead) TestPropertyRead.getBean("testconfig");

        return "<p> Java Rest Web Service JSB ...testing spring config reader "+ testPropertyRead.printAll()
                + "</p>";

        //return "<p> Java Rest Web Service JSB ...testing spring config reader "+ ((TestPropertyRead)TestPropertyRead.getBean("testconfig")).printAll()+ "</p>";       
    }


    /**
     * Similarly one can download text data also
     * @return
     */

    @Path("/downloadimage")
    @GET
    @Produces("image/png")
    public Response downloadimage()
    {
        logger.debug("inside downloadimage function call");
    File file = new File("C:\\swamishiva.jpg");     

    ResponseBuilder response = Response.ok((Object) file);
    response.header("Content-Disposition",
        "attachment; filename=image_from_server.png");
    return response.build();

    }

       }


===============================================================================

testpropertyRead.java

    package com.restfulservice.gateway;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Component
public class TestPropertyRead 
{
    //private static ApplicationContext CONTEXT;




    private String name;
    private String address;

    public TestPropertyRead()
    {

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String printAll() {
        System.out.println("name:" + name + " Address:" + address);

        return "name:" + name + " Address:" + address;
    }


}

2 个答案:

答案 0 :(得分:0)

我对spring很新,但通常会发现当我有自动连接属性的空指针时,这是因为组件扫描失败了。

也许看看这个问题Spring Boot MVC并检查一下是否有帮助?

我总是忘记的是@EnableAutoConfiguration。

答案 1 :(得分:0)

Pom需要支持休息和弹簧整合:

<dependency>
    <groupId>org.glassfish.jersey.ext</groupId>
    <artifactId>jersey-spring3</artifactId>
    <version>2.4.1</version>
    <exclusions>
    <exclusion>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
    </exclusion>            
    <exclusion>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
    </exclusion>
    <exclusion>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
    </exclusion>
    </exclusions>            
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>2.4.1</version>
</dependency>