当前位置: 首页 > 知识库问答 >
问题:

如何在Spring Boot中使用@bean创建或配置Rest模板

步弘和
2023-03-14

我想在Spring Boot应用程序的配置类中使用@bean注释将RestTemplate定义为应用程序bean。

我正在调用我的应用流程中不同地方的4个rest服务。当前,我在每次请求时都创建RestTemplate。是否有一种方法可以使用@bean将其定义为应用程序bean,并使用@autowired注入应用程序bean?

出现这个问题的主要原因是,我可以使用@bean定义RestTemplate,但当我用@autowired注入它时,我会丢失所有已定义的拦截器(拦截器不会被调用。)

配置类

@Bean(name = "appRestClient")
public RestTemplate getRestClient() {

    RestTemplate  restClient = new RestTemplate(
        new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));

    List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
    interceptors.add(new RestServiceLoggingInterceptor());
    restClient.setInterceptors(interceptors);

    return restClient;
}

服务类别

public class MyServiceClass {

    @Autowired
    private RestTemplate appRestClient;

    public String callRestService() {
        // create uri, method response objects
        String restResp = appRestClient.getForObject(uri, method, response);
        // do something with the restResp
        // return String
    }
}

看来我的interceptors在这种配置下根本没有被调用。但是RestTemplate能够调用REST服务并获得响应。

共有1个答案

秦凯定
2023-03-14

从拦截器的名字来看,我猜你在做一些记录?您可能会错过日志级别配置。我使用1.3.6.release版本创建了一个小应用程序来检查您的配置是否工作。

在这个类中,我定义了RestTemplatebean和带有日志记录的拦截器。

package com.example;

// imports...

@SpringBootApplication
public class TestApplication {

    private static final Logger LOGGER = LoggerFactory.getLogger(TestApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }

    @Bean(name = "appRestClient")
    public RestTemplate getRestClient() {
        RestTemplate restClient = new RestTemplate(
                new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));

        // Add one interceptor like in your example, except using anonymous class.
        restClient.setInterceptors(Collections.singletonList((request, body, execution) -> {

            LOGGER.debug("Intercepting...");
            return execution.execute(request, body);
        }));

        return restClient;
    }
}

为了使日志记录工作,我还必须在application.properties中设置正确的调试级别。

logging.level.com.example=DEBUG
@Service
public class SomeService {

    private final RestTemplate appRestClient;

    @Autowired
    public SomeService(@Qualifier("appRestClient") RestTemplate appRestClient) {
        this.appRestClient = appRestClient;
    }

    public String callRestService() {
        return appRestClient.getForObject("http://localhost:8080", String.class);
    }
}

和一个endpoint来测试这一点。

@RestController
public class SomeController {

    private final SomeService service;

    @Autowired
    public SomeController(SomeService service) {
        this.service = service;
    }

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String testEndpoint() {
        return "hello!";
    }

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String test() {
        return service.callRestService();
    }
}

通过对http://localhost:8080/test执行get请求,我应该希望得到正在打印的字符串Hello!(服务调用http://localhost:8080,它返回Hello!并将其发送回我)。带有记录器的拦截器还在控制台中打印出intercepting...

 类似资料:
  • 我在这里阅读了spring文档中关于@Bean Lite模式的部分内容,根据我的理解,如果config被注释为component,那么spring就不会创建这个config的代理类,并且这个类中所有配置的bean都被视为普通方法调用。但是,根据这个示例,Spring为bean创建了代理,该代理被注释为@Transactional并配置在@Component类内部 这意味着ProxyBean是由cg

  • 我在学习Spring Boot时遇到了一些编码问题;我想添加一个像Spring3.x那样的CharacterEncodingFilter。就像这样:

  • 我需要将旧式spring项目迁移到springboot。假设下面的代码片段我必须迁移到Spring Boot风格。 在这里我的问题,如何将下面的抽象bean转换为@Bean?

  • 我正在使用Spring3.0 restTemboard通过调用post方法消费json webservice。 我们的应用程序部署在WAS服务器中,并试图通过创建与TLS1的套接字连接来连接producer。0.但是,现在producer只支持TLS1。1和TLS1。2. 如何强制restTempate使用TLS1。1或TLS 1.2。 通常,对于apache httpClient代码,创建自定义

  • 我正在创建JavaMailSender的bean类,并自动拥有javamailsender,但我得到错误 我不能为bean id="mail Sender"创建bean类。我在过去的两天里一直在努力,请让我离开它。 和错误页 组织。springframework。豆。工厂BeanCreationException:创建名为“employeeController”的bean时出错:自动连线依赖项的注

  • 如何配置SpringBoot、SpringDataJPA、SpringTest和Hibernate来为保存和检索对象的单元测试创建、使用和删除给定的PostgreSQL模式? 在测试开始之前,Spring测试应该为测试创建数据库模式。每个测试方法都应该在单个事务中运行,并且在它完成后,测试方法应该回滚所有数据库操作。在所有测试方法结束时,测试应该删除模式。 在目前的形式中,传递,但在模式中创建表,