0

I'm trying get a class to request data from a rest api periodically to check if the data I have in my database is still up to date.

The documentation says that to enable scheduling I should add the @EnableScheduling annotation to a configuration class, and that I will then be able to use the @Scheduled annotation on any spring managed bean in the container.

It all works, but I don't fully understand what any spring managed bean in the container means. Right now I declared the bean like this in the configuration class (the class CapsuleRestApi is the class responsible for requesting data from the api)

@Bean
public CapsuleRestApi capsuleDatabaseJpa() {
    return new CapsuleRestApi();
}

And then I used this method in the CapsuleRestApi class

@Scheduled(fixedDelay = 2000)
public void refresh() {
    // refresh and check changes
}

Is there another way to make it work without adding the method as bean? I don't fully understand why it works with the bean method.

pvpkiran
  • 25,582
  • 8
  • 87
  • 134
DreamsInHD
  • 403
  • 5
  • 17

1 Answers1

1

what any spring managed bean in the container means.

This means that, spring should know about this class when it starts. If you put @Scheduled on a method in a class which spring doesn't scan during startup, this annotation doesn't have any significance.

For example. Consider you have a class like this

class NotManagedBean {

   @Scheduled
   public void scheduler() {
      .....
   }
}

You will see that this scheduled method is never executed. Because, Spring container doesn't know about this class. That is because it was not scanned. Which is due do the fact that it is not a spring bean.

Now add @Component or Service on the class. This will make the class a spring bean and it will work.

When you do @Bean that means, you are declaring a bean. And hence it works.

Hope that is clear

pvpkiran
  • 25,582
  • 8
  • 87
  • 134
  • There's still one thing I don't get: I understand the class has to be declared a bean, but why in the form of creating a method that creates a new instance? It would make more sense to me to add an annotion to the class to declare it a bean – DreamsInHD Mar 17 '18 at 21:20
  • That is just one way of declaring a bean. As i mentioned above, you can declare it in other ways. – pvpkiran Mar 17 '18 at 23:26
  • Okay I get it now, thanks! – DreamsInHD Mar 18 '18 at 08:45