每次在 Spring Boot 中调用时都会创建一个新的 bean 实例。

huangapple 未分类评论59阅读模式
英文:

New Obect of bean for each invocation in spring boot

问题

我正在一个Spring Boot应用程序中工作,其中我有一个控制器层,一个用于业务逻辑的服务层,然后调用进入另一个与一些外部REST服务进行交互的服务层。

在我与外部REST服务连接的最后一层,我正在使用RestTemplate,但是通过从具有一些SSL安全性和身份验证的bean获取restTemplate对象。

类似于Service C中的以下内容:

@Autowired
private RestTemplate gcssRestTemplate;

以及一个返回restTemplate对象的bean:

@Bean()
RestTemplate gcssRestTemplate(RestTemplateBuilder restTemplateBuilder)
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {

    return restTemplateBuilder.build();
}

现在我打算以某种方式进行更改,每次调用"C"服务层方法,例如getGETResponse(),我都会获得一个新的restTemplate对象,该方法实际上使用此restTemplate对象调用外部资源。

我尝试过通过作用域"prototype"创建bean,但效果与我的预期不符。

有人可以建议一种方法,通过该方法我可以指定每当在服务的最后一层(图片中的Serve C)中调用方法getGETResponse()时,都会创建一个新的restTemplate对象。

英文:

I am working in a spring boot application , where I have one controller layer , one service layer for business logic , then call goes to another service layer which interact with some external REST services.

每次在 Spring Boot 中调用时都会创建一个新的 bean 实例。

In last layer where I am connecting with external REST services , I am using restTemplete but by getting the restTemplete object from a bean with some SSL security and authentication.

Something like this
in Service C

  @Autowired
private RestTemplate gcssRestTemplate;

and a bean which is returning the restTemplate object

@Bean()
RestTemplate gcssRestTemplate(RestTemplateBuilder restTemplateBuilder)
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {

    return restTemplateBuilder.build());
    }

Now I am intending to do it in some way where every time I will get a new object of restTemplete , for each call of "C" service level method say , getGETResponse() , which is actually using this restTemplete to calling the external world.

I tried with bean creating by scope “prototype” but it did not work as I expect.

Can any one suggest any way out by which I can specify when ever a new call invoked in last layer of service(serve c in picture) for method "getGETResponse()", a new object of restTemplete will we wared up with that.

huangapple
  • 本文由 发表于 2020年5月5日 21:22:57
  • 转载请务必保留本文链接:https://java.coder-hub.com/61614220.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定