简体   繁体   English

Spring 引导:如何更新 Bean?

[英]Spring Boot: How to Update Beans?

I have a @Bean which calls an external API at the start of the application.我有一个@Bean,它在应用程序开始时调用外部 API。 How can I have it such that it makes a new call and updates the bean on a set timer?我怎样才能让它在设定的计时器上进行新的调用并更新 bean?

@Bean
public Template apiCall()
{
    final String uri = "http://...";
    return new RestTemplate().getForObject(uri,Template.class);
}

One way is reload the template in some kind of factory bean.一种方法是在某种工厂 bean 中重新加载模板。

@Component
public class TemplateProvider {

   @Value("${template.uri}")
   private String uri;

   private Template template;

   @Autowired 
   private RestTemplate restTemplate;

   @PostConstruct
   init () {
      loadTemplate();
   }

   public synchronized void reset() {
      loadTemplate();
   }

   public synchronized Template template() {
      return template;
   }

   private void loadTemplate() {
     try {
        this.template = restTemplate.getFor...();
     } 
     catch (Exception e) {
         //
     }
   }

}

Then you can call reset() inside a @scheduled method.然后你可以在@scheduled方法中调用reset()

The only drawback to this is that callers should not keep reference of Template in their state.. Always access template via the provider to avoid inconsistency problems.唯一的缺点是调用者不应在其 state 中保留对Template的引用。始终通过提供程序访问模板以避免不一致问题。

public class Client {
   @Autowired
   private TemplateProvider templateProvider;

   public void method() {
      templateProvider.template().method();
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM