Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)
Is there any Spring 3 feature to execute some methods when the application starts for the first time? I know that I can do the trick of setting a method with @Scheduled annotation and it executes just after the startup, but then it will execute periodically.

1 Answer

0 votes
by (46k points)

If by "application startup" you mean "application context startup", then yes, there are many ways to do this, the easiest (for singletons beans, anyway) being to annotate your method with @PostConstruct. Take a look at the link to see the other options, but in summary, they are:

  • Methods annotated with @PostConstruct
  • afterPropertiesSet() as defined by the InitializingBean callback interface
  • A custom-configured init() method

Technically, these are hooks into the bean lifecycle, rather than the context lifecycle, but in 99% of cases, the two are equivalent.

If you need to look specifically into the context startup/shutdown, then you can implement the Lifecycle interface instead, but that's probably unnecessary.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 17, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Sep 24, 2019 in Java by Anvi (10.2k points)

Browse Categories

...