【问题标题】:Not able to autowire Spring Rest Template无法自动装配 Spring Rest 模板
【发布时间】:2016-10-17 08:44:06
【问题描述】:

下面是我的rest模板配置:

<beans:bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
    <beans:constructor-arg>
        <beans:bean class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
            <beans:property name="readTimeout" value="600000" />
            <beans:property name="connectTimeout" value="600000" />
        </beans:bean>
    </beans:constructor-arg>
    <beans:property name="messageConverters">
        <beans:list>
            <beans:bean id="byteArrayMessageConverter" class="org.springframework.http.converter.ByteArrayHttpMessageConverter">
            </beans:bean>
            <beans:bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
                <beans:property name="objectMapper">
                    <beans:ref bean="jacksonObjectMapper" />
                </beans:property>
                <beans:property name="supportedMediaTypes">
                    <beans:list>
                        <beans:value>text/plain</beans:value>
                        <beans:value>application/json</beans:value>
                    </beans:list>
                </beans:property>
            </beans:bean>


        </beans:list>
    </beans:property>
</beans:bean>

当我尝试自动装配和访问类中的模板时,我得到了一个 NPE:

@Service
public class GitService {

    @Autowired
    RestTemplate restTemplate;

    public void getTot(String url) {

        List<ResponseObject> eg = (List<ResponseObject>) restTemplate.getForObject(url,ResponseObject.class);
    }
}

例外:

SEVERE: Servlet.service() for servlet [appServlet] in context with path [/github] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
    at com.assignment.github.service.GitService.getTot(GitService.java:25)

谁能告诉我这里出了什么问题?

【问题讨论】:

  • @Autowired 不能为空。如果您使用基于组件扫描或注释的配置,您的应用程序将无法启动。如果您要自己创建 GitService 的实例,则 if 只能是 null。 IE。做new GitService()。 Spring 不会知道该实例,因此无法注入依赖项。

标签: java spring rest spring-mvc spring-rest


【解决方案1】:

请添加这些标签

<context:annotation-config/>

如果你没有

<context:component-scan base-package="<Your_base_package"/>

进入同一个配置文件。

【讨论】:

  • 为什么需要&lt;mvc:annotation-driven /&gt;?这是用于配置注释驱动的网络内容,与自动装配无关......
  • 这是我的做法,当我遇到这个问题时,我会这样做。下次我将只使用第一个@M.Deinum
  • 如果你已经有 &lt;context:component-scan /&gt; 已经暗示了 &lt;context:annotation-config /&gt;,你就不需要了。
猜你喜欢
  • 2017-12-18
  • 2016-09-27
  • 2013-01-29
  • 1970-01-01
  • 2023-04-08
  • 2012-12-04
  • 2013-11-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多