Junior
How to execute code after Spring has injected all dependencies of a bean?
sobes.tech AI
Answer from AI
In Spring, to execute code after all dependencies of a bean have been injected, you can use the InitializingBean interface or the @PostConstruct annotation.
Example with @PostConstruct:
import javax.annotation.PostConstruct;
import org.springframework.stereotype.Component;
@Component
public class MyBean {
@PostConstruct
public void init() {
// This method will be called after all dependencies are injected
System.out.println("All dependencies are injected, initialization can proceed");
}
}
Alternatively, you can implement the InitializingBean interface and override the afterPropertiesSet() method:
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
@Component
public class MyBean implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
// Code that will run after dependencies are injected
}
}
Both methods guarantee that the code will execute after Spring completes injecting all dependencies into the bean.