Search code examples
javaspringspring-bootspring-scheduled

Components method only called once at start


I have s Spring Component. How can I call a method only one at start and never again?

I use Scheduler but I am only aware of periodically calls.

Sure I can set the interval very high - but maybe there is a better solution for my problem.

@Component
public class Test
{
    @Scheduled (fixedDelay = 100000)
    public void foo ()
    {
    }
}

Solution

  • There are a few ways to handle this; PostConstruct is the most straightforward.

    You just add a PostConstruct annotation to your method, dropping the @Scheduled annotation altogether. Spring will execute this method after it creates the bean and is done initializing it.

    @PostConstruct
    public void foo ()
    {
    }