Sobes.tech
Junior — Middle

How can you ensure automatic initialization of a Spring Bean object at application startup?

sobes.tech AI

Answer from AI

To automatically initialize a Spring Bean at application startup, you can use the @PostConstruct annotation in the bean class. This method will be called immediately after the bean is created and dependencies are injected.

Alternatively, you can implement the InitializingBean interface and override the afterPropertiesSet() method, which is called after all properties are set.

Example with @PostConstruct:

@Component
public class MyBean {

    @PostConstruct
    public void init() {
        // initialization code
        System.out.println("Bean initialized");
    }
}

Thus, when the Spring application starts, it will automatically call the init() method after creating the bean.

How can you ensure automatic initialization of a… - sobes.tech