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
InitializingBeaninterface and override theafterPropertiesSet()method. - Use the
@PostConstructannotation on a method that should be executed after initialization. - Specify an initialization method in the configuration via the
initMethodattribute.
Example with @PostConstruct:
@Component
public class MyBean {
@PostConstruct
public void init() {
// code that will run immediately after Bean creation
}
}