javaspringspring-bootrestget-mapping

Spring Boot consuming webservice with scheduler


Hello I have RestController anotated class with a method like this:

@Bean
@GetMapping
@Scope("prototype")
public Info[] setInfo()
{
    return m_restTemplate.getForObject(m_url, Info[].class);
}

Here I can get info[] and I use it in my SQL table.

But web service continuously update Info objects that I get from m_url. I can only get this Info[] once at spring boot initialisation. And I have to restart the API to update my SQL table.

Here is a sample code with autowired info[]

@Autowired
public Info[] Infos;

public InfoRepository(NamedParameterJdbcTemplate m_jdbcTemplate) {
    this.m_jdbcTemplate = m_jdbcTemplate;
}


public <S extends Info> S update(S info) {
    m_jdbcTemplate.update(UPDATE_SQL, new BeanPropertySqlParameterSource(info));

    return info;
}

But when I try to run, I get the same object obviously. How can I call @GetMapping annotated method every time in scheduler :

private final InfoRepository m_infoRepository;
private ArrayList<Info> m_Infos;

public void update()
{
    Timer timer = new Timer();

    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            m_coinInfos.forEach(i -> m_infoRepository.update(i));
        }
    }, 0, 2000);
}

Solution

  • You can use @Scheuled annotation like this:

    @Scheduled(fixedDelay = 1000)
    public void updateInfo() {
       // update call
    }
    

    In this case, it will be call update every second.

    The other way is to change WS to broadcast information about change, but in that case you need access to code of that WS.


    Edit after OP comment

    In this case, you need some kind of Value Object pattern. Encapsulate your Info[] in some container, e.g. InfoStore:

    @Component
    class InfoStore{
    
       private Info[] info;
    
       public Info[] getInfo(){
         //...
       }
    }
    

    That will be injected into your beans. Now you can update Info[] every time you need and use every method you want. Your „main” bean will be injected once, but it „guts” can be change any time you need.