Java spring autowire 不工作返回空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23549322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 23:49:40  来源:igfitidea点击:

spring autowire is not working returning null

javaspringautowired

提问by user3590506

i'm learning spring now. here's my sample code. i'm using jersey, spring, hibernate, and mysql for my REST service.

我现在正在学习春天。这是我的示例代码。我的 REST 服务使用 jersey、spring、hibernate 和 mysql。

CustomerServiceImpl.javawhich is REST endpoint (partial code)

CustomerServiceImpl.java这是 REST 端点(部分代码)

package com.samples.service.impl;

@Path("customers")
public class CustomerServiceImpl implements CustomerService {

    private static Logger logger = Logger.getLogger(CustomerServiceImpl.class);

    @Autowired
    CustomerBO customerBO;

here is CustomerBOImpl.java(partial code)

这是CustomerBOImpl.java(部分代码)

package com.samples.BO.impl;

@Component
public class CustomerBOImpl implements CustomerBO {

    @Autowired
    CustomerDAO customerDAO;

    @Autowired
    CustomerAdapter customerAdapter;

CustomerDAOImpl.class package com.samples.DAO.impl;

CustomerDAOImpl.class 包 com.samples.DAO.impl;

@Repository
public class CustomerDAOImpl implements CustomerDAO {

this is applicationContext.xml

这是 applicationContext.xml

<?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:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    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
              http://www.springframework.org/schema/tx 
              http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">

<context:property-placeholder location="classpath*:database.properties"/>
<context:component-scan base-package="com.samples"/>
<context:annotation-config />

</beans>    

this is first few lines of exception i'm getting.

这是我得到的前几行异常。

http-bio-8090-exec-1] [class: CustomerServiceImpl] INFO  - list all customers
[http-bio-8090-exec-1] [class: CustomerServiceImpl] INFO  - customerBO is null
May 08, 2014 10:55:29 AM com.sun.jersey.spi.container.ContainerResponse mapMappableContainerException
SEVERE: The RuntimeException could not be mapped to a response, re-throwing to the HTTP container
java.lang.NullPointerException
    at com.samples.service.impl.CustomerServiceImpl.getAllCustomers(CustomerServiceImpl.java:40)
    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.invoke(JavaMethodInvokerFactory.java:60)
    at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvo

this is web.xml

这是 web.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
    <display-name>Employee Service</display-name>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>

        classpath*:applicationContext.xml
        </param-value>
    </context-param>

    <context-param>
        <param-name>initializeContextOnStartup</param-name> 
        <param-value>true</param-value> 
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
    </listener>

    <servlet>
        <servlet-name>jersey-serlvet</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
            <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>com.samples.service</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>jersey-serlvet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>


</web-app>

so if i'm understanding how this works correctly, i'm configuring xmlto have my components autoscanned by providing the package under which i want to run autoscan. and for objects that i want to autowire. in CustomerServiceImplclass, i use @autowired for customerBOobject which should have been scanned by @Component annotation on CustomerBOImpl.class definition. can you please help why my auto-scan is not picking up autowired customerBO object? thanks.

因此,如果我了解它是如何正确工作的,我configuring xml将通过提供我想在其下运行自动扫描的包来自动扫描我的组件。以及我想要自动装配的对象。在CustomerServiceImpl课堂上,我使用 @autowired 作为customerBO对象,该对象应该由 CustomerBOImpl.class 定义上的 @Component 注释扫描。你能帮我为什么我的自动扫描没有拿起自动装配的 customerBO 对象吗?谢谢。

回答by m3th0dman

Spring only know to autowire fields that have been marked as beans. From your code CustomerDAOis not a bean. For example to define it as a bean in the xml configuration file you need to add <bean id="customerDao" class="com.packagesNames.CustomerDaoImpl"/> in the xml file.or to have the class annotated with @Componentor to have it defined with @Beanin a @Configurationclass.

Spring 只知道自动装配已标记为 bean 的字段。从你的代码CustomerDAO不是一个bean。例如,要将其定义为 xml 配置文件中的 bean,您需要添加<bean id="customerDao" class="com.packagesNames.CustomerDaoImpl"/> in the xml file.或对类进行注释@Component@Bean@Configuration类中对其进行定义。

回答by Chris Thompson

I suspect the problem is your CustomerServiceImplclass is being instantiated outside of Spring, either by the servlet container or explicitly in your code. You need to either have Spring instantiate it (by making it a bean, etc) or use <context:spring-configured/>. I'm not sure if the latter will work if the servlet container instantiates the object as it will likely depend on the order in which things occur...

我怀疑问题是您的CustomerServiceImpl类是在 Spring 之外实例化的,要么由 servlet 容器实例化,要么在您的代码中显式实例化。您需要让 Spring 实例化它(通过使其成为 abean等)或使用<context:spring-configured/>. 如果servlet容器实例化对象,我不确定后者是否会起作用,因为它可能取决于事情发生的顺序......

回答by Victor Lyuboslavsky

Jersey 2 and Spring integration is now supported.

现在支持 Jersey 2 和 Spring 集成。

Jersey Docs: Chapter 22. Spring DI

Jersey 文档:第 22 章 Spring DI

Blog: Implementing Jersey 2 Spring Integration

博客:实施 Jersey 2 Spring 集成

Sample App: Jersey's Hello World Spring WebApp

示例应用程序:Jersey 的 Hello World Spring WebApp

However, as of this writing, Spring beans can't be injected directly into JAX-RS classes by using Spring XML configuration. Annotations (@Autowired, etc.) must be used.

但是,在撰写本文时,还不能使用 Spring XML 配置将 Spring bean 直接注入 JAX-RS 类。@Autowired必须使用注释(等)。

回答by Sumit

I had the same problem. My injected bean in the resource class was always coming as NULL.

我有同样的问题。我在资源类中注入的 bean 总是作为NULL.

I spent 2 days trying to figure it out why I can't inject the Spring Bean into the JAX-RS resource class. Then I found the below in the Jersey documentation:

我花了 2 天时间试图弄清楚为什么我不能将 Spring Bean 注入 JAX-RS 资源类。然后我在Jersey 文档中找到了以下内容

"Limitations:

Spring beans can't be injected directly into JAX-RS classes by using Spring XML configuration"

“限制:

Spring bean 不能通过使用 Spring XML 配置直接注入 JAX-RS 类"

Note: I was using Jersey 2 and Spring 3.x in my project.

注意:我在我的项目中使用 Jersey 2 和 Spring 3.x。