Sobes.tech
Junior — Middle

How can you perform a specific action immediately upon Bean creation in Spring?

sobes.tech AI

Answer from AI

In Spring, there are several ways to perform an action immediately after creating a Bean:

  • Implement the InitializingBean interface and override the afterPropertiesSet() method.
  • Use the @PostConstruct annotation on a method that should be executed after initialization.
  • Specify an initialization method in the configuration via the initMethod attribute.

Example with @PostConstruct:

@Component
public class MyBean {
    @PostConstruct
    public void init() {
        // code that will run immediately after Bean creation
    }
}