如何在泽西应用

时间:2016-12-15 11:01:34

标签: java spring jersey

以下是带有spring的Jersey应用程序的代码。我正在使用resttemplate来检查休息终点。 我想使用Appconfig class配置resttemplate。我的意思是当创建resttemplate实例时,应该从appconfig restTemplate()函数创建它。有可能吗?

//JerseyApplication.java
public class JerseyApplication extends ResourceConfig
{
    private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(JerseyApplication.class);

    /**
     * Initialized the jersey application.
     */
    public JerseyApplication()
    {
        register(JerseyFeature.class);
        register(JsonFeature.class);
        register(BeanValidationFeature.class);
        register(new RequestResponseLoggingFilter(LOG));
    }
}

//TestResource.java
@Component("apiTestResource")
@PropertySource("classpath:default.properties")
@Singleton
public class TestResource{
    @javax.ws.rs.core.Context
    private javax.ws.rs.core.UriInfo uriInfo;

    @Autowired
    private RestTemplate restTemplate;

    private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(TestResource.class);
    public Response post() {

        Response response = null;

        UriComponentsBuilder uriComponents = UriComponentsBuilder.fromHttpUrl("http://test.com")

        HttpEntity<String> requestPayload = new HttpEntity<String>("test string");

        ResponseEntity<String> responseEntity = util.postSyncRequest(restTemplate,uriComponents.build().encode().toUri(),
                requestPayload);

        response = Response.ok().entity(responseEntity.getBody().toString()).build();
        return response;
    }
}
//Util.java
public class Util {

    private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(Util.class);
    public ResponseEntity<String> postSyncRequest(RestTemplate restTemplate ,URI uri, HttpEntity<String> requestPayload){
        ResponseEntity<String> responseEntity = null;
        try{
            responseEntity = restTemplate.postForEntity(uri, requestPayload,String.class);
        }catch(Exception ex){
            LOG.error("Error in post call " + ex.getMessage());
        }
        return responseEntity;
    }
}
//AppConfig.java
@Configuration
public class AppConfig {
        @Bean
        RestTemplate restTemplate() {
            SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
            return new RestTemplate(requestFactory);
        }
}
//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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- include Service SDK libraries -->
    <import resource="classpath:/META-INF/libraries-spring.xml" />

    <!-- include Service SDK API-Console helpers -->
    <import resource="classpath*:/META-INF/api-console-spring.xml" />

    <!-- import placeholder values from property files and environment, see
        default.properties -->
    <context:property-placeholder
        location="classpath:/default.properties,classpath*:test.properties" />

    <!-- take annotation-based configuration into account, when instantiating
        beans -->
    <context:annotation-config />

    <bean id="RestTemplate" class="org.springframework.web.client.RestTemplate">
    </bean>

</beans>

更新: 在尝试@jobin推荐的后,我收到了以下错误

[ERROR] [o.s.web.context.ContextLoader] [] Context initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'apiCurrencyS4hanaResource': Unsatisfied dependency expressed through field 'restTemplate': No qualifying bean of type [org.springframework.web.client.RestTemplate] found for dependency [org.springframework.web.client.RestTemplate]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.web.client.RestTemplate] found for dependency [org.springframework.web.client.RestTemplate]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

1 个答案:

答案 0 :(得分:0)

是的,有可能,你所做的是正确的,但不需要SimpleClientHttpRequestFactory,你可以简单地创建一个RestTemplate的实例,如下所示,它将创建一个singleton bean你可以autowire到其他春天components

import org.springframework.web.client.RestTemplate;

@Configuration
public class AppConfig {

    @Bean
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
}